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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #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: 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 #17
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 #18
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 #19
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 #20
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 #21
Source File: BaseEntityManagerFunctionalTestCase.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static String getEntityName(Class<?> entityClass) {
  String name = entityClass.getAnnotation(Entity.class).name();
  if (name == null || name.isEmpty()) {
    name = entityClass.getSimpleName();
  }
  return name;
}
 
Example #22
Source File: PersistenceXmlTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyClassTags_containOnlyRequiredClasses() {
  ImmutableList<Class> managedClassed = PersistenceXmlUtility.getManagedClasses();

  ImmutableList<Class> unnecessaryClasses =
      managedClassed.stream()
          .filter(
              clazz ->
                  !clazz.isAnnotationPresent(Entity.class)
                      && !AttributeConverter.class.isAssignableFrom(clazz))
          .collect(toImmutableList());

  ImmutableSet<Class> duplicateClasses =
      managedClassed.stream()
          .filter(clazz -> Collections.frequency(managedClassed, clazz) > 1)
          .collect(toImmutableSet());

  expect
      .withMessage("Found duplicate <class> tags defined in persistence.xml.")
      .that(duplicateClasses)
      .isEmpty();

  expect
      .withMessage(
          "Found unnecessary <class> tags defined in persistence.xml. Only entity class and"
              + " implementation of AttributeConverter are required to be added in"
              + " persistence.xml.")
      .that(unnecessaryClasses)
      .isEmpty();
}
 
Example #23
Source File: DaoSupport.java    From bbs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 获取实体名称,由上面的方法调用
 * @param <T>
 * @param entityClass 实体类
 * @return
 */
protected <T> String getEntityName(Class<T> entityClass){
	//默认情况下实体名称为这个类的简单名称,即实体类上的这个标志@Entity
	String entityname = entityClass.getSimpleName();
	//获取实体类Entity注解上的属性,如Entity(name="xxx")这种情况
	Entity entity = entityClass.getAnnotation(Entity.class);
	//判断实体类Entity注解上是否设置了name属性
	if(entity.name() != null && !"".equals(entity.name())){
		//把实体名称修改为它的属性值
		entityname = entity.name();
	}
	return entityname;
}
 
Example #24
Source File: DefaultJpaEntityMetadata.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public String getEntityName() {

    Entity entity = domainType.getAnnotation(Entity.class);
    boolean hasName = null != entity && StringUtils.hasText(entity.name());

    return hasName ? entity.name() : domainType.getSimpleName();
}
 
Example #25
Source File: RepositoryImpl.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
private String entityName(Class<?> entityClass) {
    String name = entityClass.getDeclaredAnnotation(Entity.class).name();
    if (Strings.isNullOrEmpty(name)) {
        return entityClass.getSimpleName();
    } else {
        return name;
    }
}
 
Example #26
Source File: EnhancePersistenceXmlWriter.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private static List<Class<?>> scanEnhanceClass() throws Exception {
	List<Class<?>> list = new ArrayList<Class<?>>();
	try (ScanResult scanResult = new ClassGraph().enableAnnotationInfo().scan()) {
		List<ClassInfo> classInfos = scanResult.getClassesWithAnnotation(Entity.class.getName());
		for (ClassInfo info : classInfos) {
			list.add(Class.forName(info.getName()));
		}
		return list.stream().sorted(Comparator.comparing(Class::getName)).collect(Collectors.toList());
	}
}
 
Example #27
Source File: TestBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public ClassPath getCompileClassPath() {
    if (compileClassPath == null) {
        URL statelessAnnotationURL = Entity.class.getProtectionDomain().getCodeSource().getLocation();
        compileClassPath = ClassPathSupport.createClassPath(new URL[] { FileUtil.getArchiveRoot(statelessAnnotationURL) });
    }
    return compileClassPath;
}
 
Example #28
Source File: Hibernate5DDLExporter.java    From zhcet-web with Apache License 2.0 5 votes vote down vote up
private MetadataSources mapAnnotatedClasses(ServiceRegistry serviceRegistry) {
    MetadataSources sources = new MetadataSources(serviceRegistry);

    final Reflections reflections = new Reflections();
    for (final Class<?> mappedSuperClass : reflections.getTypesAnnotatedWith(MappedSuperclass.class)) {
        sources.addAnnotatedClass(mappedSuperClass);
        System.out.println("Mapped = " + mappedSuperClass.getName());
    }
    for (final Class<?> entityClasses : reflections.getTypesAnnotatedWith(Entity.class)) {
        sources.addAnnotatedClass(entityClasses);
        System.out.println("Mapped = " + entityClasses.getName());
    }
    return sources;
}
 
Example #29
Source File: EclipselinkStaticWeaveMojo.java    From eclipselink-maven-plugin with Apache License 2.0 5 votes vote down vote up
private Set<String> findEntities(String[] allBasePackages, final URL[] classPath)
{
    final Set<String> result = new TreeSet<>();

    try (final ScanResult scanResult = new ClassGraph().whitelistPackages(allBasePackages).enableAnnotationInfo().overrideClasspath((Object[]) classPath).scan())
    {
        result.addAll(extract(scanResult, Entity.class));
        result.addAll(extract(scanResult, MappedSuperclass.class));
        result.addAll(extract(scanResult, Embeddable.class));
        result.addAll(extract(scanResult, Converter.class));
    }
    return result;
}
 
Example #30
Source File: FieldHelper.java    From tk-mybatis with MIT 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;
}