Java Code Examples for javax.persistence.Entity

The following are top voted examples for showing how to use javax.persistence.Entity. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: crnk-framework   File: JpaModule.java   Source Code and License 7 votes vote down vote up
/**
 * Sets up relationship repositories for the given document class. In case
 * of a mapper the resource class might not correspond to the entity class.
 */
private void setupRelationshipRepositories(Class<?> resourceClass, boolean mapped) {
	if (context.getResourceInformationBuilder().accept(resourceClass)) {
		ResourceInformation information = context.getResourceInformationBuilder().build(resourceClass);


		for (ResourceField field : information.getFields()) {
			if (field.getResourceFieldType() != ResourceFieldType.RELATIONSHIP) {
				continue;
			}

			Class<?> attrType = field.getElementType();
			boolean isEntity = attrType.getAnnotation(Entity.class) != null;
			if (isEntity) {
				setupRelationshipRepositoryForEntity(resourceClass, field);
			}
			else {
				setupRelationshipRepositoryForResource(resourceClass, field);
			}
		}
	}
}
 
Example 2
Project: testing_security_development_enterprise_systems   File: DeleterEJB.java   Source Code and License 7 votes vote down vote up
public void deleteEntities(Class<?> entity){

        if(entity == null || entity.getAnnotation(Entity.class) == null){
            throw new IllegalArgumentException("Invalid non-entity class");
        }

        String name = entity.getSimpleName();

        /*
            Note: we passed as input a Class<?> instead of a String to
            avoid SQL injection. However, being here just test code, it should
            not be a problem. But, as a good habit, always be paranoiac about
            security, above all when you have code that can delete the whole
            database...
         */

        Query query = em.createQuery("delete from " + name);
        query.executeUpdate();
    }
 
Example 3
Project: jspare-vertx-ms-blueprint   File: JDBCProvider.java   Source Code and License 7 votes vote down vote up
public EntityManagerFactory build() {

		Properties properties = createProperties();

		DefaultPersistenceUnitInfoImpl persistenceUnitInfo = new DefaultPersistenceUnitInfoImpl(JSPARE_GATEWAY_DATASOURCE);
		persistenceUnitInfo.setProperties(properties);

		// Using RESOURCE_LOCAL for manage transactions on DAO side.
		persistenceUnitInfo.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);

		// Add all entities to configuration
		ClassAnnotationMatchProcessor processor = (c) -> persistenceUnitInfo.addAnnotatedClassName(c);
		ClasspathScannerUtils.scanner(ALL_SCAN_QUOTE).matchClassesWithAnnotation(Entity.class, processor)
				.scan(NUMBER_CLASSPATH_SCANNER_THREADS);

		Map<String, Object> configuration = new HashMap<>();
		properties.forEach((k, v) -> configuration.put((String) k, v));

		EntityManagerFactory entityManagerFactory = persistenceProvider.createContainerEntityManagerFactory(persistenceUnitInfo,
				configuration);
		return entityManagerFactory;
	}
 
Example 4
Project: amv-access-api-poc   File: RepositoryConfig.java   Source Code and License 6 votes vote down vote up
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
    //config.setBasePath("api");

    try {
        config.exposeIdsFor(UserEntity.class);
        ClassPathUtils.streamClassesAnnotatedWith(UserEntity.class, Entity.class)
                .peek(clazz -> log.debug("enable @Id json mapping for entity {}", clazz.getSimpleName()))
                .forEach(config::exposeIdsFor);
    } catch (IOException e) {
        throw new IllegalStateException("Could not exposeIds for @Entity classes");
    }
}
 
Example 5
Project: tipi-engine   File: HibernateMetaDataHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Retourne les classes d'une package
 *
 * @param packageName
 * @return
 * @throws Exception
 */
public static List<Class> getClasses(String packageName) {
    final List<Class> list = new ArrayList<>();

    final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AssignableTypeFilter(Object.class));
    final Set<BeanDefinition> bds = scanner.findCandidateComponents(packageName);
    try {
        for (BeanDefinition bd : bds) {
            final Class<?> tc = Class.forName(bd.getBeanClassName());
            if (tc.getAnnotation(Entity.class) != null) {
                list.add(tc);
            }
        }
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
    return list;
}
 
Example 6
Project: aries-jpa   File: JPAWeavingHook.java   Source Code and License 6 votes vote down vote up
@Override
public void weave(WovenClass wovenClass) {
    BundleWiring wiring = wovenClass.getBundleWiring();
    Bundle bundle = wiring.getBundle();
    ClassLoader cl = wiring.getClassLoader();
    Collection<ClassTransformer> transformersToTry = getTransformers(bundle);
    for (ClassTransformer transformer : transformersToTry) {
        if (transformClass(wovenClass, cl, transformer)) {
            LOGGER.info("Weaving " + wovenClass.getClassName() + " using " + transformer.getClass().getName());
            break;
        }
    }
    Class<?> dClass = wovenClass.getDefinedClass();
    if (transformersToTry.isEmpty() && dClass != null && dClass.getAnnotation(Entity.class) != null) {
        LOGGER.warn("Loading " + wovenClass.getClassName() + " before transformer is present");
    }
}
 
Example 7
Project: testing_security_development_enterprise_systems   File: DeleterService.java   Source Code and License 6 votes vote down vote up
public void deleteEntities(Class<?> entity){

        if(entity == null || entity.getAnnotation(Entity.class) == null){
            throw new IllegalArgumentException("Invalid non-entity class");
        }

        String name = entity.getSimpleName();

        /*
            Note: we passed as input a Class<?> instead of a String to
            avoid SQL injection. However, being here just test code, it should
            not be a problem. But, as a good habit, always be paranoiac about
            security, above all when you have code that can delete the whole
            database...
         */

        Query query = em.createQuery("delete from " + name);
        query.executeUpdate();
    }
 
Example 8
Project: testing_security_development_enterprise_systems   File: DeleterEJB.java   Source Code and License 6 votes vote down vote up
public void deleteEntities(Class<?> entity){

        if(entity == null || entity.getAnnotation(Entity.class) == null){
            throw new IllegalArgumentException("Invalid non-entity class");
        }

        String name = entity.getSimpleName();

        /*
            Note: we passed as input a Class<?> instead of a String to
            avoid SQL injection. However, being here just test code, it should
            not be a problem. But, as a good habit, always be paranoiac about
            security, above all when you have code that can delete the whole
            database...
         */

        Query query = em.createQuery("delete from " + name);
        query.executeUpdate();
    }
 
Example 9
Project: testing_security_development_enterprise_systems   File: DeleterEJB.java   Source Code and License 6 votes vote down vote up
public void deleteEntities(Class<?> entity){

        if(entity == null || entity.getAnnotation(Entity.class) == null){
            throw new IllegalArgumentException("Invalid non-entity class");
        }

        String name = entity.getSimpleName();

        /*
            Note: we passed as input a Class<?> instead of a String to
            avoid SQL injection. However, being here just test code, it should
            not be a problem. But, as a good habit, always be paranoiac about
            security, above all when you have code that can delete the whole
            database...
         */

        Query query = em.createQuery("delete from " + name);
        query.executeUpdate();
    }
 
Example 10
Project: testing_security_development_enterprise_systems   File: ResetEjb.java   Source Code and License 6 votes vote down vote up
private void deleteEntities(Class<?> entity){

        if(entity == null || entity.getAnnotation(Entity.class) == null){
            throw new IllegalArgumentException("Invalid non-entity class");
        }

        String name = entity.getSimpleName();

        /*
            Note: we passed as input a Class<?> instead of a String to
            avoid SQL injection. However, being here just test code, it should
            not be a problem. But, as a good habit, always be paranoiac about
            security, above all when you have code that can delete the whole
            database...
         */

        Query query = em.createQuery("delete from " + name);
        query.executeUpdate();
    }
 
Example 11
Project: testing_security_development_enterprise_systems   File: ResetEjb.java   Source Code and License 6 votes vote down vote up
private void deleteEntities(Class<?> entity){

        if(entity == null || entity.getAnnotation(Entity.class) == null){
            throw new IllegalArgumentException("Invalid non-entity class");
        }

        String name = entity.getSimpleName();

        /*
            Note: we passed as input a Class<?> instead of a String to
            avoid SQL injection. However, being here just test code, it should
            not be a problem. But, as a good habit, always be paranoiac about
            security, above all when you have code that can delete the whole
            database...
         */

        Query query = em.createQuery("delete from " + name);
        query.executeUpdate();
    }
 
Example 12
Project: testing_security_development_enterprise_systems   File: ResetService.java   Source Code and License 6 votes vote down vote up
private void deleteEntities(Class<?> entity){

        if(entity == null || entity.getAnnotation(Entity.class) == null){
            throw new IllegalArgumentException("Invalid non-entity class");
        }

        String name = entity.getSimpleName();

        /*
            Note: we passed as input a Class<?> instead of a String to
            avoid SQL injection. However, being here just test code, it should
            not be a problem. But, as a good habit, always be paranoiac about
            security, above all when you have code that can delete the whole
            database...
         */

        Query query = em.createQuery("delete from " + name);
        query.executeUpdate();
    }
 
Example 13
Project: lams   File: Configuration.java   Source Code and License 6 votes vote down vote up
public AnnotatedClassType addClassType(XClass clazz) {
	AnnotatedClassType type;
	if ( clazz.isAnnotationPresent( Entity.class ) ) {
		type = AnnotatedClassType.ENTITY;
	}
	else if ( clazz.isAnnotationPresent( Embeddable.class ) ) {
		type = AnnotatedClassType.EMBEDDABLE;
	}
	else if ( clazz.isAnnotationPresent( javax.persistence.MappedSuperclass.class ) ) {
		type = AnnotatedClassType.EMBEDDABLE_SUPERCLASS;
	}
	else {
		type = AnnotatedClassType.NONE;
	}
	classTypes.put( clazz.getName(), type );
	return type;
}
 
Example 14
Project: lams   File: AnnotationBinder.java   Source Code and License 6 votes vote down vote up
private static boolean isEntityClassType(XClass clazzToProcess, AnnotatedClassType classType) {
	if ( AnnotatedClassType.EMBEDDABLE_SUPERCLASS.equals( classType ) //will be processed by their subentities
			|| AnnotatedClassType.NONE.equals( classType ) //to be ignored
			|| AnnotatedClassType.EMBEDDABLE.equals( classType ) //allow embeddable element declaration
			) {
		if ( AnnotatedClassType.NONE.equals( classType )
				&& clazzToProcess.isAnnotationPresent( org.hibernate.annotations.Entity.class ) ) {
			LOG.missingEntityAnnotation( clazzToProcess.getName() );
		}
		return false;
	}

	if ( !classType.equals( AnnotatedClassType.ENTITY ) ) {
		throw new AnnotationException(
				"Annotated class should have a @javax.persistence.Entity, @javax.persistence.Embeddable or @javax.persistence.EmbeddedSuperclass annotation: " + clazzToProcess
						.getName()
		);
	}

	return true;
}
 
Example 15
Project: lams   File: AbstractPropertyHolder.java   Source Code and License 6 votes vote down vote up
private void buildHierarchyColumnOverride(XClass element) {
	XClass current = element;
	Map<String, Column[]> columnOverride = new HashMap<String, Column[]>();
	Map<String, JoinColumn[]> joinColumnOverride = new HashMap<String, JoinColumn[]>();
	Map<String, JoinTable> joinTableOverride = new HashMap<String, JoinTable>();
	while ( current != null && !mappings.getReflectionManager().toXClass( Object.class ).equals( current ) ) {
		if ( current.isAnnotationPresent( Entity.class ) || current.isAnnotationPresent( MappedSuperclass.class )
				|| current.isAnnotationPresent( Embeddable.class ) ) {
			//FIXME is embeddable override?
			Map<String, Column[]> currentOverride = buildColumnOverride( current, getPath() );
			Map<String, JoinColumn[]> currentJoinOverride = buildJoinColumnOverride( current, getPath() );
			Map<String, JoinTable> currentJoinTableOverride = buildJoinTableOverride( current, getPath() );
			currentOverride.putAll( columnOverride ); //subclasses have precedence over superclasses
			currentJoinOverride.putAll( joinColumnOverride ); //subclasses have precedence over superclasses
			currentJoinTableOverride.putAll( joinTableOverride ); //subclasses have precedence over superclasses
			columnOverride = currentOverride;
			joinColumnOverride = currentJoinOverride;
			joinTableOverride = currentJoinTableOverride;
		}
		current = current.getSuperclass();
	}

	holderColumnOverride = columnOverride.size() > 0 ? columnOverride : null;
	holderJoinColumnOverride = joinColumnOverride.size() > 0 ? joinColumnOverride : null;
	holderJoinTableOverride = joinTableOverride.size() > 0 ? joinTableOverride : null;
}
 
Example 16
Project: lams   File: JPAOverriddenAnnotationReader.java   Source Code and License 6 votes vote down vote up
private Entity getEntity(Element tree, XMLContext.Default defaults) {
	if ( tree == null ) {
		return defaults.canUseJavaAnnotations() ? getPhysicalAnnotation( Entity.class ) : null;
	}
	else {
		if ( "entity".equals( tree.getName() ) ) {
			AnnotationDescriptor entity = new AnnotationDescriptor( Entity.class );
			copyStringAttribute( entity, tree, "name", false );
			if ( defaults.canUseJavaAnnotations()
					&& StringHelper.isEmpty( (String) entity.valueOf( "name" ) ) ) {
				Entity javaAnn = getPhysicalAnnotation( Entity.class );
				if ( javaAnn != null ) {
					entity.setValue( "name", javaAnn.name() );
				}
			}
			return AnnotationFactory.create( entity );
		}
		else {
			return null; //this is not an entity
		}
	}
}
 
Example 17
Project: VoxelGamesLib   File: HibernatePersistenceProvider.java   Source Code and License 6 votes vote down vote up
@Override
public void start() {
    StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
            .applySetting("hibernate.connection.username", config.persistence.user)
            .applySetting("hibernate.connection.password", config.persistence.pass)
            .applySetting("hibernate.connection.driver_class", config.persistence.driver)
            .applySetting("hibernate.connection.url", config.persistence.url)
            .applySetting("hibernate.dialect", config.persistence.dialect)
            .applySetting("hibernate.connection.pool_size", config.persistence.pool_size + "")
            .applySetting("hibernate.hbm2ddl.auto", "update")
            .applySetting("hibernate.show_sql", config.persistence.showSQL + "")
            .build();

    MetadataSources sources = new MetadataSources(registry);

    Timings.time("RegisterDBEntities", () ->
            new Reflections().getTypesAnnotatedWith(Entity.class).forEach(sources::addAnnotatedClass));

    try {
        Metadata metadata = sources.buildMetadata();
        sessionFactory = metadata.buildSessionFactory();
    } catch (Exception e) {
        StandardServiceRegistryBuilder.destroy(registry);
        e.printStackTrace();
    }
}
 
Example 18
Project: ismartonline   File: PaginatorQueryHelper.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * @param manager {@link EntityManager} to create the query
 * @param klass klass to guess the list query and count query
 * @param currentPage 
 * @param max max number of elements
 * @return
 */
public <T> PaginatedList list(EntityManager manager, Class<T> klass,
      int currentPage, int max)
{

   if (!klass.isAnnotationPresent(Entity.class))
   {
      throw new IllegalArgumentException("Your entity is not annotated with @Entity");
   }

   TypedQuery<T> listQuery = manager.createQuery(
         "select o from " + klass.getSimpleName() + " o", klass);

   TypedQuery<Number> countQuery = manager.createQuery(
         "select count(1) from " + klass.getSimpleName() + " o",
         Number.class);

   return list(listQuery, countQuery, currentPage, max);
}
 
Example 19
Project: api-server-seed   File: TableSearchColumnHelper.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param entityClass
 * @param fieldList
 * @return
 */
private static List<Field> getAllField(Class<?> entityClass, List<Field> fieldList) {
    if (fieldList == null) {
        fieldList = new LinkedList<Field>();
    }
    if (entityClass.equals(Object.class)) {
        return fieldList;
    }
    Field[] fields = entityClass.getDeclaredFields();
    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            fieldList.add(field);
        }
    }
    Class<?> superClass = entityClass.getSuperclass();
    if (superClass != null
            && !superClass.equals(Object.class)
            && (superClass.isAnnotationPresent(Entity.class)
            || (!Map.class.isAssignableFrom(superClass)
            && !Collection.class.isAssignableFrom(superClass)))) {
        return getAllField(entityClass.getSuperclass(), fieldList);
    }
    return fieldList;
}
 
Example 20
Project: jpa-unit   File: EntityUtilsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetEntityClassFromNodeLabelsHavingTheLabelDeclaredByTheTableAnnotationWithoutInheritance() throws Exception {
    final String simpleClassName = "EntityClass";
    final String nodeLabel = "ENTITY_CLASS";

    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName);
    jClass.annotate(Entity.class);
    jClass.annotate(Table.class).param("name", nodeLabel);

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

    final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name());

    final Class<?> clazz = EntityUtils.getEntityClassFromNodeLabels(Arrays.asList(nodeLabel), Arrays.asList(entityClass));

    assertThat(clazz, equalTo(entityClass));
}
 
Example 21
Project: jpa-unit   File: EntityUtilsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetNamesOfIdPropertiesFromASingleClassHavingAFieldAnnotatedWithId() throws Exception {
    // GIVEN
    final String simpleClassName = "EntityClass";
    final String idPropertyName = "key";

    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName);
    jClass.annotate(Entity.class);
    jClass.field(JMod.PRIVATE, String.class, idPropertyName).annotate(Id.class);

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

    final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name());

    // WHEN
    final List<String> namesOfIdProperties = EntityUtils.getNamesOfIdProperties(entityClass);

    // THEN
    assertThat(namesOfIdProperties.size(), equalTo(1));
    assertThat(namesOfIdProperties, hasItem(idPropertyName));
}
 
Example 22
Project: jpa-unit   File: EntityUtilsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetNamesOfIdPropertiesFromASingleClassHavingAMethodAnnotatedWithId() throws Exception {
    // GIVEN
    final String simpleClassName = "EntityClass";
    final String idPropertyName = "key";

    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName);
    jClass.annotate(Entity.class);
    jClass.method(JMod.PUBLIC, jCodeModel.VOID, "getKey").annotate(Id.class);

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

    final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name());

    // WHEN
    final List<String> namesOfIdProperties = EntityUtils.getNamesOfIdProperties(entityClass);

    // THEN
    assertThat(namesOfIdProperties.size(), equalTo(1));
    assertThat(namesOfIdProperties, hasItem(idPropertyName));
}
 
Example 23
Project: jpa-unit   File: GraphElementFactoryTest.java   Source Code and License 6 votes vote down vote up
@BeforeClass
public static void generateTestModel() throws Exception {
    final JCodeModel jCodeModel = new JCodeModel();

    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "A");
    jClass.annotate(Entity.class);
    jClass.field(JMod.PRIVATE, Long.class, "id").annotate(Id.class);
    jClass.field(JMod.PRIVATE, String.class, "value");

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

    entityAClass = loadClass(testFolder.getRoot(), jClass.name());
}
 
Example 24
Project: cibet   File: DefaultExecutor.java   Source Code and License 6 votes vote down vote up
@Override
public void jpaResultListQuery(EventMetadata metadata, Query query, CEntityManager entityManager) {
   List<?> result = new ArrayList<Object>();

   if (!Context.requestScope().isPlaying()) {
      result = query.getResultList();
      for (Object object : result) {
         if (object != null && entityManager.isLoadEager()
               && (object.getClass().getAnnotation(Embeddable.class) != null
                     || object.getClass().getAnnotation(Entity.class) != null)) {
            CibetUtil.loadLazyEntities(object, object.getClass());
            List<Object> references = new ArrayList<Object>();
            references.add(object);
            CibetUtil.deepDetach(object, references);
         }
      }
   }
   metadata.getResource().setResultObject(result);
}
 
Example 25
Project: gorm-hibernate5   File: GrailsDomainBinder.java   Source Code and License 6 votes vote down vote up
@Override
public void contribute(InFlightMetadataCollector metadataCollector, IndexView jandexIndex) {
    MetadataBuildingOptions options = metadataCollector.getMetadataBuildingOptions();
    ClassLoaderService classLoaderService = options.getServiceRegistry().getService(ClassLoaderService.class);

    final ClassLoaderAccess classLoaderAccess = new ClassLoaderAccessImpl(
            options.getTempClassLoader(),
            classLoaderService
    );

    this.metadataBuildingContext = new MetadataBuildingContextRootImpl(
            options,
            classLoaderAccess,
            metadataCollector
    );

        java.util.Collection<PersistentEntity> persistentEntities = hibernateMappingContext.getPersistentEntities();
    for (PersistentEntity persistentEntity : persistentEntities) {
        if(!persistentEntity.getJavaClass().isAnnotationPresent(Entity.class)) {
            if(ConnectionSourcesSupport.usesConnectionSource(persistentEntity, dataSourceName) && persistentEntity.isRoot()) {
                bindRoot((HibernatePersistentEntity) persistentEntity, metadataCollector, sessionFactoryName);
            }
        }
    }
}
 
Example 26
Project: cuba   File: CubaClientTestCase.java   Source Code and License 6 votes vote down vote up
protected List<String> getClasses(Resource[] resources) {
    List<String> classNames = new ArrayList<>();

    for (Resource resource : resources) {
        if (resource.isReadable()) {
            MetadataReader metadataReader;
            try {
                metadataReader = metadataReaderFactory.getMetadataReader(resource);
            } catch (IOException e) {
                throw new RuntimeException("Unable to read metadata resource", e);
            }

            AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
            if (annotationMetadata.isAnnotated(com.haulmont.chile.core.annotations.MetaClass.class.getName())
                    || annotationMetadata.isAnnotated(MappedSuperclass.class.getName())
                    || annotationMetadata.isAnnotated(Entity.class.getName())) {
                ClassMetadata classMetadata = metadataReader.getClassMetadata();
                classNames.add(classMetadata.getClassName());
            }
        }
    }
    return classNames;
}
 
Example 27
Project: warpdb   File: ClassUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Scan @Entity classes in base packages.
 * 
 * @param basePackages
 *            base package names.
 * @return List of entity class.
 */
public static List<Class<?>> scanEntities(String... basePackages) {
	ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
	provider.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
	List<Class<?>> classes = new ArrayList<>();
	for (String basePackage : basePackages) {
		Set<BeanDefinition> beans = provider.findCandidateComponents(basePackage);
		for (BeanDefinition bean : beans) {
			try {
				classes.add(Class.forName(bean.getBeanClassName()));
			} catch (ClassNotFoundException e) {
				throw new RuntimeException(e);
			}
		}
	}
	return classes;
}
 
Example 28
Project: Unicorn   File: RestNotificationRule.java   Source Code and License 6 votes vote down vote up
@Override
/*
 * No longer persisting RestNotificationForQuery 
 */
public boolean trigger(final Map<Object, Serializable> eventObject) {
	try {
		final JSONObject event = NotificationRuleUtils.toJSON(eventObject);
		//final RestNotificationForQuery notification = new RestNotificationForQuery(event.toString(), this);
		// no longer storing the notifications, as they were causing errors with JPA
		// probably because the entity was configured incorrectly. However, as no one
		// ever looks them up again, we should stop persisting these anyway.
		//notification.save();

		Client client = ClientBuilder.newClient();
		WebTarget target = client.target(this.notificationPath);

		Response response = target.request().post(javax.ws.rs.client.Entity.json(event.toString()));
		return response.getStatus() == 200;
	} catch (UnsupportedJsonTransformation e) {
		e.printStackTrace();
	}
	return false;
}
 
Example 29
Project: jspare-vertx-ms-blueprint   File: JDBCProvider.java   Source Code and License 6 votes vote down vote up
public EntityManagerFactory build() {

		Properties properties = createProperties();

		DefaultPersistenceUnitInfoImpl persistenceUnitInfo = new DefaultPersistenceUnitInfoImpl(JSPARE_GATEWAY_DATASOURCE);
		persistenceUnitInfo.setProperties(properties);

		// Using RESOURCE_LOCAL for manage transactions on DAO side.
		persistenceUnitInfo.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);

		// Add all entities to configuration
		ClassAnnotationMatchProcessor processor = (c) -> persistenceUnitInfo.addAnnotatedClassName(c);
		ClasspathScannerUtils.scanner(ALL_SCAN_QUOTE).matchClassesWithAnnotation(Entity.class, processor)
				.scan(NUMBER_CLASSPATH_SCANNER_THREADS);

		Map<String, Object> configuration = new HashMap<>();
		properties.forEach((k, v) -> configuration.put((String) k, v));

		EntityManagerFactory entityManagerFactory = persistenceProvider.createContainerEntityManagerFactory(persistenceUnitInfo,
				configuration);
		return entityManagerFactory;
	}
 
Example 30
Project: dropwizard-hikaricp   File: ManagedPooledDataSourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testInsertAndQuery() throws Exception {
    final TestEntity entity = TestEntity.builder()
            .key("abc").build();

    final Response response = this.client
            .target(String.format("http://localhost:%d/test", this.RULE.getLocalPort()))
            .request()
            .post(javax.ws.rs.client.Entity.json(entity));
    assertThat(response.getStatus()).isEqualTo(Status.CREATED.getStatusCode());

    final TestEntity createdEntity = this.client
            .target(String.format("http://localhost:%d/test/1", this.RULE.getLocalPort()))
            .request()
            .get(TestEntity.class);
    assertThat(createdEntity).isEqualToIgnoringGivenFields(entity, "id");
}
 
Example 31
Project: ontobrowser   File: CuratorApprovalWeight.java   Source Code and License 6 votes vote down vote up
public static Entity valueOf(VersionedEntity entity) {
	if(entity instanceof Synonym) {
		return TERM_SYNONYM;
	}
	
	if(entity instanceof Relationship) {
		return TERM_RELATIONSHIP;
	}
	
	if(entity instanceof Term) {
		return TERM;
	}
	
	if(entity instanceof RelationshipType) {
		return RELATIONSHIP_TYPE;
	}
	
	if(entity instanceof Ontology) {
		return ONTOLOGY;
	}
	
	throw new IllegalArgumentException("Invalid entity: " + entity.getClass().getName());
}
 
Example 32
Project: metaworks_framework   File: AuditableListener.java   Source Code and License 6 votes vote down vote up
@PrePersist
public void setAuditCreatedBy(Object entity) throws Exception {
    if (entity.getClass().isAnnotationPresent(Entity.class)) {
        Field field = getSingleField(entity.getClass(), "auditable");
        field.setAccessible(true);
        if (field.isAnnotationPresent(Embedded.class)) {
            Object auditable = field.get(entity);
            if (auditable == null) {
                field.set(entity, new Auditable());
                auditable = field.get(entity);
            }
            Field temporalField = auditable.getClass().getDeclaredField("dateCreated");
            Field agentField = auditable.getClass().getDeclaredField("createdBy");
            setAuditValueTemporal(temporalField, auditable);
            setAuditValueAgent(agentField, auditable);
        }
    }
}
 
Example 33
Project: blcdemo   File: AuditableListener.java   Source Code and License 6 votes vote down vote up
@PreUpdate
public void setAuditUpdatedBy(Object entity) throws Exception {
    if (entity.getClass().isAnnotationPresent(Entity.class)) {
        Field field = getSingleField(entity.getClass(), "auditable");
        field.setAccessible(true);
        if (field.isAnnotationPresent(Embedded.class)) {
            Object auditable = field.get(entity);
            if (auditable == null) {
                field.set(entity, new Auditable());
                auditable = field.get(entity);
            }
            Field temporalField = auditable.getClass().getDeclaredField("dateUpdated");
            Field agentField = auditable.getClass().getDeclaredField("updatedBy");
            setAuditValueTemporal(temporalField, auditable);
            setAuditValueAgent(agentField, auditable);
        }
    }
}
 
Example 34
Project: metaworks_framework   File: HydratedSetup.java   Source Code and License 6 votes vote down vote up
private static String getInheritanceHierarchyRoot(Class<?> myEntityClass) {
    String myEntityName = myEntityClass.getName();
    if (inheritanceHierarchyRoots.containsKey(myEntityName)) {
        return inheritanceHierarchyRoots.get(myEntityName);
    }
    Class<?> currentClass = myEntityClass;
    boolean eof = false;
    while (!eof) {
        Class<?> superclass = currentClass.getSuperclass();
        if (superclass.equals(Object.class) || !superclass.isAnnotationPresent(Entity.class)) {
            eof = true;
        } else {
            currentClass = superclass;
        }
    }

    if (!currentClass.isAnnotationPresent(Cache.class)) {
        currentClass = myEntityClass;
    }

    inheritanceHierarchyRoots.put(myEntityName, currentClass.getName());
    return inheritanceHierarchyRoots.get(myEntityName);
}
 
Example 35
Project: xap-openspaces   File: StoreManager.java   Source Code and License 6 votes vote down vote up
/**
 * Validates the provided class' annotations.
 * Currently the only validation performed is for @Id & @SpaceId annotations
 * that must be declared on the same getter.  
 */
private void validateClassAnnotations(Class<?> type) {
    // Validation is only relevant for Entities
    if (type.getAnnotation(Entity.class) == null)
        return;
    
    for (Method getter : type.getMethods()) {
        
        if (!getter.getName().startsWith("get"))
            continue;
        
        SpaceId spaceId = getter.getAnnotation(SpaceId.class);
        boolean hasJpaId = getter.getAnnotation(Id.class) != null || getter.getAnnotation(EmbeddedId.class) != null; 
        if (spaceId != null || hasJpaId) {                
            if (!hasJpaId || spaceId == null)
                throw new IllegalArgumentException("SpaceId and Id annotations must both be declared on the same property in JPA entities in type: " + type.getName());
            if (spaceId.autoGenerate()) {
                GeneratedValue generatedValue = getter.getAnnotation(GeneratedValue.class);
                if (generatedValue == null || generatedValue.strategy() != GenerationType.IDENTITY)
                    throw new IllegalArgumentException(
                            "SpaceId with autoGenerate=true annotated property should also have a JPA GeneratedValue annotation with strategy = GenerationType.IDENTITY.");
            }
            break;
        }
    }        
}
 
Example 36
Project: iris   File: TerminalServiceImpl.java   Source Code and License 6 votes vote down vote up
BigInteger determineUniqueId() {

        String entityName = Terminal.class.getAnnotation(Entity.class).name();
        BigInteger nextUniqueId = uniqueIdSequenceService.getNextId(entityName);

        boolean isUniqueIdAlreadyAssigned = terminalRepository.findByUniqueId(nextUniqueId) != null;

        while (isUniqueIdAlreadyAssigned) {
            // In this loop we increment the ID by ourselves to avoid write-accesses to the DB for performance.
            LOG.warn("Terminal uniqueId {} already assigned - trying next uniqueId", nextUniqueId);
            nextUniqueId = nextUniqueId.add(BigInteger.ONE);

            if (terminalRepository.findByUniqueId(nextUniqueId) == null) {
                isUniqueIdAlreadyAssigned = false;
                uniqueIdSequenceService.setNextId(entityName, nextUniqueId);
            }
        }

        return nextUniqueId;
    }
 
Example 37
Project: SparkCommerce   File: AdminAuditableListener.java   Source Code and License 6 votes vote down vote up
@PrePersist
public void setAuditCreatedBy(Object entity) throws Exception {
    if (entity.getClass().isAnnotationPresent(Entity.class)) {
        Field field = getSingleField(entity.getClass(), "auditable");
        field.setAccessible(true);
        if (field.isAnnotationPresent(Embedded.class)) {
            Object auditable = field.get(entity);
            if (auditable == null) {
                field.set(entity, new AdminAuditable());
                auditable = field.get(entity);
            }
            Field temporalCreatedField = auditable.getClass().getDeclaredField("dateCreated");
            Field temporalUpdatedField = auditable.getClass().getDeclaredField("dateUpdated");
            Field agentField = auditable.getClass().getDeclaredField("createdBy");
            setAuditValueTemporal(temporalCreatedField, auditable);
            setAuditValueTemporal(temporalUpdatedField, auditable);
            setAuditValueAgent(agentField, auditable);
        }
    }
}
 
Example 38
Project: SparkCommerce   File: AdminAuditableListener.java   Source Code and License 6 votes vote down vote up
@PreUpdate
public void setAuditUpdatedBy(Object entity) throws Exception {
    if (entity.getClass().isAnnotationPresent(Entity.class)) {
        Field field = getSingleField(entity.getClass(), "auditable");
        field.setAccessible(true);
        if (field.isAnnotationPresent(Embedded.class)) {
            Object auditable = field.get(entity);
            if (auditable == null) {
                field.set(entity, new AdminAuditable());
                auditable = field.get(entity);
            }
            Field temporalField = auditable.getClass().getDeclaredField("dateUpdated");
            Field agentField = auditable.getClass().getDeclaredField("updatedBy");
            setAuditValueTemporal(temporalField, auditable);
            setAuditValueAgent(agentField, auditable);
        }
    }
}
 
Example 39
Project: SparkCommerce   File: AuditableListener.java   Source Code and License 6 votes vote down vote up
@PrePersist
public void setAuditCreatedBy(Object entity) throws Exception {
    if (entity.getClass().isAnnotationPresent(Entity.class)) {
        Field field = getSingleField(entity.getClass(), "auditable");
        field.setAccessible(true);
        if (field.isAnnotationPresent(Embedded.class)) {
            Object auditable = field.get(entity);
            if (auditable == null) {
                field.set(entity, new Auditable());
                auditable = field.get(entity);
            }
            Field temporalField = auditable.getClass().getDeclaredField("dateCreated");
            Field agentField = auditable.getClass().getDeclaredField("createdBy");
            setAuditValueTemporal(temporalField, auditable);
            setAuditValueAgent(agentField, auditable);
        }
    }
}
 
Example 40
Project: SparkCommerce   File: AuditableListener.java   Source Code and License 6 votes vote down vote up
@PreUpdate
public void setAuditUpdatedBy(Object entity) throws Exception {
    if (entity.getClass().isAnnotationPresent(Entity.class)) {
        Field field = getSingleField(entity.getClass(), "auditable");
        field.setAccessible(true);
        if (field.isAnnotationPresent(Embedded.class)) {
            Object auditable = field.get(entity);
            if (auditable == null) {
                field.set(entity, new Auditable());
                auditable = field.get(entity);
            }
            Field temporalField = auditable.getClass().getDeclaredField("dateUpdated");
            Field agentField = auditable.getClass().getDeclaredField("updatedBy");
            setAuditValueTemporal(temporalField, auditable);
            setAuditValueAgent(agentField, auditable);
        }
    }
}
 
Example 41
Project: dionysus   File: EntityIDTest.java   Source Code and License 6 votes vote down vote up
@Test
public void makeSureEntityIDCanbeDetect() {
	Metamodel model = entityManager.getMetamodel();
	final Reflections reflections = new Reflections(EntityIDTest.class.getPackage().getName());
	Set<Class<?>> entities = reflections.getTypesAnnotatedWith(Entity.class);

	for (Class<?> entity : entities) {
		EntityType<?> entityType = model.entity(entity);
		Class<?> id = entityType.getIdType().getJavaType();
		System.out.println(entityType);
		if (entity.equals(InvalidEntity.class)) {
			Assert.assertEquals(id, Serializable.class);
		} else {
			Assert.assertNotEquals(id, Serializable.class);
		}
	}
}
 
Example 42
Project: zstack   File: SqlIndexGenerator.java   Source Code and License 6 votes vote down vote up
private void collectIndex(Class entity) {
    List<Field> fs;
    Class superClass = entity.getSuperclass();
    if (superClass.isAnnotationPresent(Entity.class) || entity.isAnnotationPresent(EO.class)) {
        // parent class or EO class is also an entity, it will take care of its foreign key,
        // so we only do our own foreign keys;
        fs = FieldUtils.getAnnotatedFieldsOnThisClass(Index.class, entity);
    } else {
        fs = FieldUtils.getAnnotatedFields(Index.class, entity);
    }

    List<IndexInfo> keyInfos = indexMap.get(entity);
    if (keyInfos == null) {
        keyInfos = new ArrayList<IndexInfo>();
        indexMap.put(entity, keyInfos);
    }

    for (Field f : fs) {
        keyInfos.add(new IndexInfo(entity, f));
    }
}
 
Example 43
Project: iris   File: SeaportServiceImpl.java   Source Code and License 6 votes vote down vote up
BigInteger determineUniqueId() {

        String entityName = Seaport.class.getAnnotation(Entity.class).name();
        BigInteger nextUniqueId = uniqueIdSequenceService.getNextId(entityName);

        boolean isUniqueIdAlreadyAssigned = seaportRepository.findByUniqueId(nextUniqueId) != null;

        while (isUniqueIdAlreadyAssigned) {
            // In this loop we increment the ID by ourselves to avoid write-accesses to the DB for performance.
            LOG.warn("Terminal uniqueId {} already assigned - trying next uniqueId", nextUniqueId);
            nextUniqueId = nextUniqueId.add(BigInteger.ONE);

            if (!(seaportRepository.findByUniqueId(nextUniqueId) != null)) {
                isUniqueIdAlreadyAssigned = false;
                uniqueIdSequenceService.setNextId(entityName, nextUniqueId);
            }
        }

        return nextUniqueId;
    }
 
Example 44
Project: elide   File: PermissionExecutorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testPassAnyFieldAwareFailOperationSuccessCommit() {
    @Entity
    @Include
    @UpdatePermission(expression = "deny all AND passingCommit")
    class Model {
        @Id
        public Long id;

        @UpdatePermission(expression = "deny all OR passingCommit")
        public String field = "some data";
    }

    PersistentResource resource = newResource(new Model(), Model.class);
    RequestScope requestScope = resource.getRequestScope();
    requestScope.getPermissionExecutor().checkPermission(UpdatePermission.class, resource);
    requestScope.getPermissionExecutor().executeCommitChecks();
}
 
Example 45
Project: blcdemo   File: AdminAuditableListener.java   Source Code and License 6 votes vote down vote up
@PrePersist
public void setAuditCreatedBy(Object entity) throws Exception {
    if (entity.getClass().isAnnotationPresent(Entity.class)) {
        Field field = getSingleField(entity.getClass(), getAuditableFieldName());
        field.setAccessible(true);
        if (field.isAnnotationPresent(Embedded.class)) {
            Object auditable = field.get(entity);
            if (auditable == null) {
                field.set(entity, new AdminAuditable());
                auditable = field.get(entity);
            }
            Field temporalCreatedField = auditable.getClass().getDeclaredField("dateCreated");
            Field temporalUpdatedField = auditable.getClass().getDeclaredField("dateUpdated");
            Field agentField = auditable.getClass().getDeclaredField("createdBy");
            setAuditValueTemporal(temporalCreatedField, auditable);
            setAuditValueTemporal(temporalUpdatedField, auditable);
            setAuditValueAgent(agentField, auditable);
        }
    }
}
 
Example 46
Project: elide   File: PermissionExecutorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testPassAnySpecificFieldAwareFailOperationSuccessCommit() {
    @Entity
    @Include
    @UpdatePermission(expression = "deny all AND passingCommit")
    class Model {
        @Id
        public Long id;

        @UpdatePermission(expression = "deny all OR passingCommit")
        public String field = "some data";
    }

    PersistentResource resource = newResource(new Model(), Model.class);
    RequestScope requestScope = resource.getRequestScope();
    requestScope.getPermissionExecutor().checkSpecificFieldPermissions(resource, null, UpdatePermission.class, "field");
    requestScope.getPermissionExecutor().executeCommitChecks();
}
 
Example 47
Project: elide   File: PermissionExecutorTest.java   Source Code and License 6 votes vote down vote up
@Test(expectedExceptions = {ForbiddenAccessException.class})
public void testFailAllSpecificFieldAwareSuccessOperationFailCommit() {
    @Entity
    @Include
    @UpdatePermission(expression = "allow all")
    class Model {
        @Id
        public Long id;

        @UpdatePermission(expression = "allow all AND FailAtCommit")
        public String field = "some data";
    }

    PersistentResource resource = newResource(new Model(), Model.class);
    RequestScope requestScope = resource.getRequestScope();
    requestScope.getPermissionExecutor().checkSpecificFieldPermissions(resource, null, UpdatePermission.class, "field");
    requestScope.getPermissionExecutor().executeCommitChecks();
}
 
Example 48
Project: blcdemo   File: AuditableListener.java   Source Code and License 6 votes vote down vote up
@PrePersist
public void setAuditCreatedBy(Object entity) throws Exception {
    if (entity.getClass().isAnnotationPresent(Entity.class)) {
        Field field = getSingleField(entity.getClass(), "auditable");
        field.setAccessible(true);
        if (field.isAnnotationPresent(Embedded.class)) {
            Object auditable = field.get(entity);
            if (auditable == null) {
                field.set(entity, new Auditable());
                auditable = field.get(entity);
            }
            Field temporalField = auditable.getClass().getDeclaredField("dateCreated");
            Field agentField = auditable.getClass().getDeclaredField("createdBy");
            setAuditValueTemporal(temporalField, auditable);
            setAuditValueAgent(agentField, auditable);
        }
    }
}
 
Example 49
Project: git-webapp   File: EntityOperator.java   Source Code and License 6 votes vote down vote up
Optional<EntityUpdateInfo> getEntityUpdateInfo(Object object) {
  if (object.getClass().getAnnotation(Entity.class) == null) {
    throw new EntityUpdateInfoException("エンティティを指定してください:" + object.getClass().getName());
  }
  Field[] fields = object.getClass().getDeclaredFields();
  Optional<Field> match = Arrays.stream(fields)
      .filter(field -> EntityUpdateInfo.class.isAssignableFrom(field.getType()))
      .findFirst();

  return match.map(field -> {
    field.setAccessible(true);
    try {
        if (field.get(object) == null) {
          field.set(object, field.getType().newInstance());
        }
        return (EntityUpdateInfo) field.get(object);
    } catch (IllegalArgumentException | IllegalAccessException | InstantiationException e) {
        e.printStackTrace();
        throw new EntityUpdateInfoException("更新者情報の登録に失敗しました:" + object.getClass().getName());
    }
  });
}
 
Example 50
Project: elide   File: CanPaginateVisitorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testComplexTrueExpression() throws Exception {
    @Entity
    @Include
    class Book {
        @ReadPermission(expression =
                "(Filter Expression Check AND False User Check) OR (Filter Expression Check OR NOT False User Check)")
        public String title;
    }

    EntityDictionary dictionary = new EntityDictionary(checkMappings);
    dictionary.bindEntity(Book.class);
    RequestScope scope = mock(RequestScope.class);

    Assert.assertTrue(CanPaginateVisitor.canPaginate(Book.class, dictionary, scope));
}
 
Example 51
Project: elide   File: CanPaginateVisitorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testMultipleFieldsNoPagination() throws Exception {
    @Entity
    @Include
    class Book {
        @ReadPermission(expression = "Filter Expression Check")
        public String title;

        @ReadPermission(expression = "In Memory Check")
        public Date publicationDate;
    }

    EntityDictionary dictionary = new EntityDictionary(checkMappings);
    dictionary.bindEntity(Book.class);
    RequestScope scope = mock(RequestScope.class);

    Assert.assertFalse(CanPaginateVisitor.canPaginate(Book.class, dictionary, scope));
}
 
Example 52
Project: elide   File: CanPaginateVisitorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testMultipleFieldsPagination() throws Exception {
    @Entity
    @Include
    @ReadPermission(expression = "In Memory Check")
    class Book {
        @ReadPermission(expression = "Filter Expression Check")
        public String title;

        @ReadPermission(expression = "Filter Expression Check")
        public Date publicationDate;
    }

    EntityDictionary dictionary = new EntityDictionary(checkMappings);
    dictionary.bindEntity(Book.class);
    RequestScope scope = mock(RequestScope.class);

    Assert.assertTrue(CanPaginateVisitor.canPaginate(Book.class, dictionary, scope));
}
 
Example 53
Project: dropwizard-entitymanager   File: ScanningEntityManagerBundle.java   Source Code and License 6 votes vote down vote up
private static ImmutableList<Class<?>> findEntityClassesFromDirectory(String path, String... paths) {
    @SuppressWarnings("unchecked")
    final AnnotationAcceptingListener asl = new AnnotationAcceptingListener(Entity.class);
    final PackageNamesScanner scanner = new PackageNamesScanner(merge(path, paths), true);

    while (scanner.hasNext()) {
        final String next = scanner.next();
        if (asl.accept(next)) {
            try (final InputStream in = scanner.open()) {
                asl.process(next, in);
            } catch (IOException e) {
                throw new RuntimeException("AnnotationAcceptingListener failed to process scanned resource: " + next);
            }
        }
    }

    final ImmutableList.Builder<Class<?>> builder = ImmutableList.builder();
    asl.getAnnotatedClasses().forEach(builder::add);

    return builder.build();
}
 
Example 54
Project: blcdemo   File: HydratedSetup.java   Source Code and License 6 votes vote down vote up
private static String getInheritanceHierarchyRoot(Class<?> myEntityClass) {
    String myEntityName = myEntityClass.getName();
    if (inheritanceHierarchyRoots.containsKey(myEntityName)) {
        return inheritanceHierarchyRoots.get(myEntityName);
    }
    Class<?> currentClass = myEntityClass;
    boolean eof = false;
    while (!eof) {
        Class<?> superclass = currentClass.getSuperclass();
        if (superclass.equals(Object.class) || !superclass.isAnnotationPresent(Entity.class)) {
            eof = true;
        } else {
            currentClass = superclass;
        }
    }

    if (!currentClass.isAnnotationPresent(Cache.class)) {
        currentClass = myEntityClass;
    }

    inheritanceHierarchyRoots.put(myEntityName, currentClass.getName());
    return inheritanceHierarchyRoots.get(myEntityName);
}
 
Example 55
Project: common-dao   File: EntityScanner.java   Source Code and License 5 votes vote down vote up
private ClassPathScanningCandidateComponentProvider createComponentScanner() {
    // Don't pull default filters (@Component, etc.):
    ClassPathScanningCandidateComponentProvider provider
            = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
    return provider;
}
 
Example 56
Project: common-dao   File: CrudTest.java   Source Code and License 5 votes vote down vote up
private ClassPathScanningCandidateComponentProvider createComponentScanner() {
    // Don't pull default filters (@Component, etc.):
    ClassPathScanningCandidateComponentProvider provider
            = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
    return provider;
}
 
Example 57
Project: common-dao   File: CrudTest.java   Source Code and License 5 votes vote down vote up
private void printMetadata(BeanDefinition beanDef) {
    try {
        Class<?> cl = Class.forName(beanDef.getBeanClassName());
        Entity findable = cl.getAnnotation(Entity.class);
        System.out.printf("Found class: %s, with meta name: %s%n",
                cl.getSimpleName(), findable.name());
    } catch (Exception e) {
        System.err.println("Got exception: " + e.getMessage());
    }
}
 
Example 58
Project: MybatisGeneatorUtil   File: FieldHelper.java   Source Code and License 5 votes vote down vote up
/**
 * 获取全部的Field,仅仅通过Field获取
 *
 * @param entityClass
 * @param fieldList
 * @param level
 * @return
 */
private List<EntityField> _getFields(Class<?> entityClass, List<EntityField> fieldList, Integer level) {
    if (fieldList == null) {
        fieldList = new ArrayList<EntityField>();
    }
    if (level == null) {
        level = 0;
    }
    if (entityClass.equals(Object.class)) {
        return fieldList;
    }
    Field[] fields = entityClass.getDeclaredFields();
    int index = 0;
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        //排除静态字段,解决bug#2
        if (!Modifier.isStatic(field.getModifiers())) {
            if (level.intValue() != 0) {
                //将父类的字段放在前面
                fieldList.add(index, new EntityField(field, null));
                index++;
            } else {
                fieldList.add(new EntityField(field, null));
            }
        }
    }
    Class<?> superClass = entityClass.getSuperclass();
    if (superClass != null
            && !superClass.equals(Object.class)
            && (superClass.isAnnotationPresent(Entity.class)
            || (!Map.class.isAssignableFrom(superClass)
            && !Collection.class.isAssignableFrom(superClass)))) {
        return _getFields(entityClass.getSuperclass(), fieldList, ++level);
    }
    return fieldList;
}
 
Example 59
Project: MybatisGeneatorUtil   File: FieldHelper.java   Source Code and License 5 votes vote down vote up
/**
 * 获取所有泛型类型映射
 *
 * @param entityClass
 */
private Map<String, Class<?>> _getGenericTypeMap(Class<?> entityClass) {
    Map<String, Class<?>> genericMap = new HashMap<String, Class<?>>();
    if (entityClass == Object.class) {
        return genericMap;
    }
    //获取父类和泛型信息
    Class<?> superClass = entityClass.getSuperclass();
    //判断superClass
    if (superClass != null
            && !superClass.equals(Object.class)
            && (superClass.isAnnotationPresent(Entity.class)
            || (!Map.class.isAssignableFrom(superClass)
            && !Collection.class.isAssignableFrom(superClass)))) {
        if (entityClass.getGenericSuperclass() instanceof ParameterizedType) {
            Type[] types = ((ParameterizedType) entityClass.getGenericSuperclass()).getActualTypeArguments();
            TypeVariable[] typeVariables = superClass.getTypeParameters();
            if (typeVariables.length > 0) {
                for (int i = 0; i < typeVariables.length; i++) {
                    if (types[i] instanceof Class) {
                        genericMap.put(typeVariables[i].getName(), (Class<?>) types[i]);
                    }
                }
            }
        }
        genericMap.putAll(_getGenericTypeMap(superClass));
    }
    return genericMap;
}
 
Example 60
Project: MybatisGeneatorUtil   File: FieldTest.java   Source Code and License 5 votes vote down vote up
/**
 * @param entityClass
 */
private static Map<String, Class<?>> _getGenericTypeMap(Class<?> entityClass) {
    Map<String, Class<?>> genericMap = new HashMap<String, Class<?>>();
    if (entityClass == Object.class) {
        return genericMap;
    }
    //获取父类和泛型信息
    Class<?> superClass = entityClass.getSuperclass();
    //判断superClass
    if (superClass != null
            && !superClass.equals(Object.class)
            && (superClass.isAnnotationPresent(Entity.class)
            || (!Map.class.isAssignableFrom(superClass)
            && !Collection.class.isAssignableFrom(superClass)))) {
        if (entityClass.getGenericSuperclass() instanceof ParameterizedType) {
            Type[] types = ((ParameterizedType) entityClass.getGenericSuperclass()).getActualTypeArguments();
            TypeVariable[] typeVariables = superClass.getTypeParameters();
            if (typeVariables.length > 0) {
                for (int i = 0; i < typeVariables.length; i++) {
                    if (types[i] instanceof Class) {
                        genericMap.put(typeVariables[i].getName(), (Class<?>) types[i]);
                    }
                }
            }
        }
        genericMap.putAll(_getGenericTypeMap(superClass));
    }
    return genericMap;
}