javax.persistence.Entity Java Examples

The following examples show how to use javax.persistence.Entity. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MybatisPersistentPropertyImpl.java    From spring-data-mybatis with Apache License 2.0 7 votes vote down vote up
/**
 * Creates a new {@link AnnotationBasedPersistentProperty}.
 * @param property must not be {@literal null}.
 * @param owner must not be {@literal null}.
 */
public MybatisPersistentPropertyImpl(Property property,
		PersistentEntity<?, MybatisPersistentProperty> owner,
		SimpleTypeHolder simpleTypeHolder) {

	super(property, owner, simpleTypeHolder);

	this.isAssociation = Lazy.of(() -> ASSOCIATION_ANNOTATIONS.stream()
			.anyMatch(this::isAnnotationPresent));
	this.usePropertyAccess = detectPropertyAccess();
	this.associationTargetType = detectAssociationTargetType();
	this.updateable = detectUpdatability();

	this.isIdProperty = Lazy.of(
			() -> ID_ANNOTATIONS.stream().anyMatch(it -> isAnnotationPresent(it)));
	this.isEntity = Lazy.of(getActualType().isAnnotationPresent(Entity.class));
}
 
Example #2
Source File: DeleterService.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 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 #3
Source File: ScaffoldableEntitySelectionWizard.java    From angularjs-addon with Eclipse Public License 1.0 6 votes vote down vote up
public static String getEntityTable(final JavaClass<?> entity)
{
   String table = entity.getName();
   if (entity.hasAnnotation(Entity.class))
   {
      Annotation<?> a = entity.getAnnotation(Entity.class);
      if (!Strings.isNullOrEmpty(a.getStringValue("name")))
      {
         table = a.getStringValue("name");
      }
      else if (!Strings.isNullOrEmpty(a.getStringValue()))
      {
         table = a.getStringValue();
      }
   }
   return table;
}
 
Example #4
Source File: EntityUtilsTest.java    From jpa-unit with Apache License 2.0 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 #5
Source File: EntityUtilsTest.java    From jpa-unit with Apache License 2.0 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 #6
Source File: ConfigurationManagerImpl.java    From zstack with Apache License 2.0 6 votes vote down vote up
private void generateVOViewSql(StringBuilder sb, Class<?> entityClass) {
    if (!entityClass.isAnnotationPresent(Entity.class)) {
        throw new IllegalArgumentException(String.format("class[%s] is annotated by @EO but not annotated by @Entity", entityClass.getName()));
    }

    EO at = entityClass.getAnnotation(EO.class);
    if (!at.needView()) {
        return;
    }

    Class EOClazz = at.EOClazz();
    List<Field> fs = FieldUtils.getAllFields(entityClass);
    sb.append(String.format("\nCREATE VIEW `zstack`.`%s` AS SELECT ", entityClass.getSimpleName()));
    List<String> cols = new ArrayList<String>();
    for (Field f : fs) {
        if (!f.isAnnotationPresent(Column.class) || f.isAnnotationPresent(NoView.class)) {
            continue;
        }
        cols.add(f.getName());
    }
    sb.append(org.apache.commons.lang.StringUtils.join(cols, ", "));
    sb.append(String.format(" FROM `zstack`.`%s` WHERE %s IS NULL;\n", EOClazz.getSimpleName(), at.softDeletedColumn()));
}
 
Example #7
Source File: EntityUtilsTest.java    From jpa-unit with Apache License 2.0 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 #8
Source File: ResetService.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 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 #9
Source File: ResetEjb.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 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 #10
Source File: ResetService.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 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
Source File: SqlIndexGenerator.java    From zstack with Apache License 2.0 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 #12
Source File: EMFUtil.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static synchronized List<String> getEntityTypes(String packages[], Class<?>... entities) {

	List<String> entityTypes = Scan.annotated(Entity.class).in(packages).getAll();

	for (Class<?> entity : entities) {
		String type = entity.getName();
		if (!entityTypes.contains(type)) {
			entityTypes.add(type);
		}
	}

	if (!entityTypes.isEmpty()) {
		Log.info("!Found " + entityTypes.size() + " JPA Entities");
	}

	return entityTypes;
}
 
Example #13
Source File: InFlightMetadataCollectorImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
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;
	}
	annotatedClassTypeMap.put( clazz.getName(), type );
	return type;
}
 
Example #14
Source File: DeleterService.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 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 #15
Source File: ResetEjb.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 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 #16
Source File: ResetEjb.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 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 #17
Source File: ResetService.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 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 #18
Source File: MetamodelAttribute.java    From spring-data-jpa-entity-graph with MIT License 6 votes vote down vote up
public Optional<MetamodelAttributeTarget> jpaEntityTarget() {
  DeclaredType attributeType = (DeclaredType) variableElement.asType();
  List<? extends TypeMirror> typeArguments = attributeType.getTypeArguments();
  // This is the lazy way of doing this. We consider that any sub interfaces of
  // javax.persistence.metamodel.Attribute
  // will declare the target type as the last type arguments.
  // e.g. MapAttribute<Brand, Long, Product> where Product is the target
  // TODO do this cleanly by browsing the class hierarchy
  DeclaredType targetType = (DeclaredType) typeArguments.get(typeArguments.size() - 1);
  TypeElement targetTypeElement = (TypeElement) targetType.asElement();

  if (targetTypeElement.getAnnotation(Entity.class) == null) {
    return Optional.empty();
  }

  return Optional.of(
      new MetamodelAttributeTarget(
          variableElement.getSimpleName().toString(), targetTypeElement));
}
 
Example #19
Source File: CubaClientTestCase.java    From cuba with Apache License 2.0 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 #20
Source File: JPAOverriddenAnnotationReader.java    From lams with GNU General Public License v2.0 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 #21
Source File: SqlForeignKeyGenerator.java    From zstack with Apache License 2.0 5 votes vote down vote up
public void generate() {
    entityClass.addAll(BeanUtils.reflections.getTypesAnnotatedWith(Entity.class));

    for (Class entity : entityClass) {
        collectForeignKeys(entity);
    }

    orderAllKeys();

    generateForeignKeys();
}
 
Example #22
Source File: StaticWeavingTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testStaticWeaving() {
    // first, scan for all files on the classpath with an @Entity or @MappedSuperClass annotation
    Reflections reflections = new Reflections(
            DocumentAttachment.class.getPackage().getName(),
            DocumentBase.class.getPackage().getName(),
            MaintenanceLock.class.getPackage().getName(),
            Message.class.getPackage().getName());
    Set<Class<?>> entityTypes = reflections.getTypesAnnotatedWith(Entity.class);
    Set<Class<?>> superTypes = reflections.getTypesAnnotatedWith(MappedSuperclass.class);
    Set<Class<?>> embeddableTypes = reflections.getTypesAnnotatedWith(Embeddable.class);

    // next, let's assert that they have been statically weaved
    assertStaticWeaved(entityTypes, superTypes, embeddableTypes);
}
 
Example #23
Source File: FieldHelper.java    From genericdao with Artistic License 2.0 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 #24
Source File: StaticWeavingTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testStaticWeaving() {
    // first, scan for all files on the classpath with an @Entity or @MappedSuperClass annotation
    Reflections reflections = new Reflections("org.kuali.rice.krad");
    Set<Class<?>> entityTypes = reflections.getTypesAnnotatedWith(Entity.class);
    Set<Class<?>> superTypes = reflections.getTypesAnnotatedWith(MappedSuperclass.class);
    Set<Class<?>> embeddableTypes = reflections.getTypesAnnotatedWith(Embeddable.class);

    // next, let's assert that they have been statically weaved
    assertStaticWeaved(entityTypes, superTypes, embeddableTypes);
}
 
Example #25
Source File: EntityBinder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void bindEjb3Annotation(Entity ejb3Ann) {
	if ( ejb3Ann == null ) throw new AssertionFailure( "@Entity should always be not null" );
	if ( BinderHelper.isEmptyAnnotationValue( ejb3Ann.name() ) ) {
		name = StringHelper.unqualify( annotatedClass.getName() );
	}
	else {
		name = ejb3Ann.name();
	}
}
 
Example #26
Source File: EntityUtilsTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetNamesOfIdPropertiesFromAClassHierarchyHavingAMethodAnnotatedWithId() throws Exception {
    // GIVEN
    final String simpleClassNameBase = "EntityClass";
    final String simpleClassNameB = "SubEntityClass";
    final String idPropertyName = "key";

    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jBaseClass = jp._class(JMod.PUBLIC, simpleClassNameBase);
    jBaseClass.annotate(Entity.class);
    jBaseClass.annotate(Inheritance.class).param("strategy", InheritanceType.TABLE_PER_CLASS);
    jBaseClass.method(JMod.PUBLIC, jCodeModel.VOID, "getKey").annotate(Id.class);

    final JDefinedClass jSubclass = jp._class(JMod.PUBLIC, simpleClassNameB)._extends(jBaseClass);
    jSubclass.annotate(Entity.class);

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

    final Class<?> subClass = loadClass(testFolder.getRoot(), jSubclass.name());

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

    // THEN
    assertThat(namesOfIdProperties.size(), equalTo(1));
    assertThat(namesOfIdProperties, hasItem(idPropertyName));
}
 
Example #27
Source File: EntityUtilsTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetNamesOfIdPropertiesFromASingleClassHavingAFieldAnnotatedWithEmbeddedId() throws Exception {
    // GIVEN
    final String simpleClassName = "EntityClass";
    final String compositeIdPropertyName = "compositeKey";
    final String id1PropertyName = "key1";
    final String id2PropertyName = "key2";

    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jIdTypeClass = jp._class(JMod.PUBLIC, "IdType");
    jIdTypeClass.annotate(Embeddable.class);
    jIdTypeClass.field(JMod.PRIVATE, Integer.class, id1PropertyName);
    jIdTypeClass.field(JMod.PRIVATE, String.class, id2PropertyName);

    final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName);
    jClass.annotate(Entity.class);
    jClass.field(JMod.PRIVATE, jIdTypeClass, compositeIdPropertyName).annotate(EmbeddedId.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(2));
    assertThat(namesOfIdProperties,
            hasItems(compositeIdPropertyName + "." + id1PropertyName, compositeIdPropertyName + "." + id2PropertyName));
}
 
Example #28
Source File: EntityUtilsTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetNamesOfIdPropertiesFromASingleClassHavingAMethodAnnotatedWithEmbeddedId() throws Exception {
    // GIVEN
    final String simpleClassName = "EntityClass";
    final String compositeIdPropertyName = "compositeKey";
    final String id1PropertyName = "key1";
    final String id2PropertyName = "key2";

    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jIdTypeClass = jp._class(JMod.PUBLIC, "IdType");
    jIdTypeClass.annotate(Embeddable.class);
    jIdTypeClass.field(JMod.PRIVATE, Integer.class, id1PropertyName);
    jIdTypeClass.field(JMod.PRIVATE, String.class, id2PropertyName);

    final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName);
    jClass.annotate(Entity.class);
    final JMethod method = jClass.method(JMod.PUBLIC, jIdTypeClass, "getCompositeKey");
    method.annotate(EmbeddedId.class);
    method.body()._return(JExpr._null());

    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(2));
    assertThat(namesOfIdProperties,
            hasItems(compositeIdPropertyName + "." + id1PropertyName, compositeIdPropertyName + "." + id2PropertyName));
}
 
Example #29
Source File: EntityUtils.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
public static String entityName(Class<?> entityClass)
{
    String result = null;
    if (entityClass.isAnnotationPresent(Entity.class))
    {
        result = entityClass.getAnnotation(Entity.class).name();
    }
    else
    {
        result = PersistenceUnitDescriptorProvider.getInstance().entityName(entityClass);
    }
    return (result != null && !"".equals(result)) ? result : entityClass.getSimpleName();
}
 
Example #30
Source File: StaticWeavingTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testStaticWeaving() {
    // first, scan for all files on the classpath with an @Entity or @MappedSuperClass annotation
    Reflections reflections = new Reflections(getClass().getPackage().getName());
    Set<Class<?>> entityTypes = reflections.getTypesAnnotatedWith(Entity.class);
    Set<Class<?>> superTypes = reflections.getTypesAnnotatedWith(MappedSuperclass.class);
    Set<Class<?>> embeddableTypes = reflections.getTypesAnnotatedWith(Embeddable.class);

    // next, let's assert that they have been statically weaved
    assertStaticWeaved(entityTypes, superTypes, embeddableTypes);
}