Java Code Examples for javax.persistence.Entity

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Easy-Cassandra, under directory /src/main/java/org/easycassandra/persistence/.

Source file: ColumnUtil.java

  18 
vote

/** 
 * Get The Column name from an Object
 * @param object - Class of the object viewed
 * @return The name of Column name if there are not will be return null
 */
public static String getColumnFamilyName(Class<?> object){
  Entity colunaFamilia=(Entity)object.getAnnotation(Entity.class);
  if (colunaFamilia != null) {
    return colunaFamilia.name().equals("") ? object.getSimpleName() : colunaFamilia.name();
  }
  return object.getSimpleName();
}
 

Example 2

From project egov-data, under directory /egov-data-hibernate/src/main/java/egov/data/hibernate/repository/support/.

Source file: HibernateEntityInformationSupport.java

  18 
vote

public String getEntityName(){
  Class<?> domainClass=getJavaType();
  Entity entity=domainClass.getAnnotation(Entity.class);
  boolean hasName=null != entity && StringUtils.hasText(entity.name());
  return hasName ? entity.name() : domainClass.getSimpleName();
}
 

Example 3

From project spring-data-jpa, under directory /src/main/java/org/springframework/data/jpa/repository/support/.

Source file: JpaEntityInformationSupport.java

  18 
vote

public String getEntityName(){
  Class<?> domainClass=getJavaType();
  Entity entity=domainClass.getAnnotation(Entity.class);
  boolean hasName=null != entity && StringUtils.hasText(entity.name());
  return hasName ? entity.name() : domainClass.getSimpleName();
}
 

Example 4

From project querydsl, under directory /querydsl-jpa/src/main/java/com/mysema/query/jpa/.

Source file: JPQLSerializer.java

  17 
vote

private void handleJoinTarget(JoinExpression je){
  if (je.getTarget() instanceof EntityPath<?>) {
    EntityPath<?> pe=(EntityPath<?>)je.getTarget();
    if (pe.getMetadata().getParent() == null) {
      Entity entityAnnotation=pe.getAnnotatedElement().getAnnotation(Entity.class);
      if (entityAnnotation != null && entityAnnotation.name().length() > 0) {
        append(entityAnnotation.name());
      }
 else       if (pe.getType().getPackage() != null) {
        String pn=pe.getType().getPackage().getName();
        String typeName=pe.getType().getName().substring(pn.length() + 1);
        append(typeName);
      }
 else {
        append(pe.getType().getName());
      }
      append(" ");
    }
  }
  handle(je.getTarget());
}
 

Example 5

From project cdi-extension-showcase, under directory /src/main/java/com/acme/vetobean/.

Source file: EntityVetoExtension.java

  15 
vote

<X>void processAnnotatedType(@Observes ProcessAnnotatedType<X> event){
  AnnotatedType<X> type=event.getAnnotatedType();
  if (type.isAnnotationPresent(Entity.class)) {
    event.veto();
  }
}
 

Example 6

From project Core_2, under directory /javaee-impl/src/main/java/org/jboss/forge/spec/javaee/jpa/.

Source file: EntityPlugin.java

  15 
vote

@SuppressWarnings("unchecked") @DefaultCommand(help="Create a JPA @Entity") public void newEntity(@Option(required=true,name="named",description="The @Entity name") final String entityName,@Option(required=false,name="package",type=PromptType.JAVA_PACKAGE,description="The package name") final String packageName,@Option(name="idStrategy",defaultValue="AUTO",description="The GenerationType name for the ID") final GenerationType idStrategy) throws Throwable {
  final PersistenceFacet jpa=project.getFacet(PersistenceFacet.class);
  final JavaSourceFacet java=project.getFacet(JavaSourceFacet.class);
  String entityPackage;
  if ((packageName != null) && !"".equals(packageName)) {
    entityPackage=packageName;
  }
 else   if (getPackagePortionOfCurrentDirectory() != null) {
    entityPackage=getPackagePortionOfCurrentDirectory();
  }
 else {
    entityPackage=shell.promptCommon("In which package you'd like to create this @Entity, or enter for default",PromptType.JAVA_PACKAGE,jpa.getEntityPackage());
  }
  JavaClass javaClass=JavaParser.create(JavaClass.class).setPackage(entityPackage).setName(entityName).setPublic().addAnnotation(Entity.class).getOrigin().addInterface(Serializable.class);
  Field<JavaClass> id=javaClass.addField("private Long id = null;");
  id.addAnnotation(Id.class);
  id.addAnnotation(GeneratedValue.class).setEnumValue("strategy",idStrategy);
  id.addAnnotation(Column.class).setStringValue("name","id").setLiteralValue("updatable","false").setLiteralValue("nullable","false");
  Field<JavaClass> version=javaClass.addField("private int version = 0;");
  version.addAnnotation(Version.class);
  version.addAnnotation(Column.class).setStringValue("name","version");
  Refactory.createGetterAndSetter(javaClass,id);
  Refactory.createGetterAndSetter(javaClass,version);
  Refactory.createToStringFromFields(javaClass,id);
  Refactory.createHashCodeAndEquals(javaClass);
  JavaResource javaFileLocation=java.saveJavaSource(javaClass);
  shell.println("Created @Entity [" + javaClass.getQualifiedName() + "]");
  shell.execute("pick-up " + javaFileLocation.getFullyQualifiedName().replace(" ","\\ "));
}
 

Example 7

From project Core_2, under directory /javaee-impl/src/main/java/org/jboss/forge/spec/javaee/jpa/.

Source file: PersistenceFacetImpl.java

  15 
vote

private List<JavaClass> findEntitiesInFolder(final DirectoryResource packageFile){
  List<JavaClass> result=new ArrayList<JavaClass>();
  if (packageFile.exists()) {
    for (    Resource<?> source : packageFile.listResources()) {
      if (source instanceof JavaResource) {
        try {
          JavaSource<?> javaClass=((JavaResource)source).getJavaSource();
          if (javaClass.hasAnnotation(Entity.class) && javaClass.isClass()) {
            result.add((JavaClass)javaClass);
          }
        }
 catch (        FileNotFoundException e) {
          throw new IllegalStateException(e);
        }
      }
    }
    for (    Resource<?> source : packageFile.listResources()) {
      if (source instanceof DirectoryResource) {
        List<JavaClass> subResults=findEntitiesInFolder((DirectoryResource)source);
        result.addAll(subResults);
      }
    }
  }
  return result;
}
 

Example 8

From project Empire, under directory /core/src/com/clarkparsia/empire/annotation/.

Source file: RdfGenerator.java

  15 
vote

/** 
 * Return the RdfClass annotation on the object.
 * @param theObj the object to get that annotation from
 * @return the objects' RdfClass annotation
 * @throws InvalidRdfException thrown if the object does not have the required annotation, does not have an @Entityannotation, or does not  {@link SupportsRdfId support Rdf Id's}
 */
private static RdfsClass asValidRdfClass(Object theObj) throws InvalidRdfException {
  if (!BeanReflectUtil.hasAnnotation(theObj.getClass(),RdfsClass.class)) {
    throw new InvalidRdfException("Specified value is not an RdfsClass object");
  }
  if (EmpireOptions.ENFORCE_ENTITY_ANNOTATION && !BeanReflectUtil.hasAnnotation(theObj.getClass(),Entity.class)) {
    throw new InvalidRdfException("Specified value is not a JPA Entity object");
  }
  asSupportsRdfId(theObj);
  return BeanReflectUtil.getAnnotation(theObj.getClass(),RdfsClass.class);
}
 

Example 9

From project grails-data-mapping, under directory /grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/model/config/.

Source file: GormMappingConfigurationStrategy.java

  15 
vote

/** 
 * Tests whether an class is a persistent entity Based on the same method in Grails core within the DomainClassArtefactHandler class
 * @param clazz The java class
 * @return True if it is a persistent entity
 */
public boolean isPersistentEntity(Class clazz){
  if (clazz == null)   return false;
  if (Closure.class.isAssignableFrom(clazz)) {
    return false;
  }
  if (Enum.class.isAssignableFrom(clazz))   return false;
  if (clazz.isAnnotationPresent(Entity.class)) {
    return true;
  }
  for (  Annotation annotation : clazz.getAnnotations()) {
    if (annotation.toString().equals("@grails.persistence.Entity()"))     return true;
  }
  Class testClass=clazz;
  boolean result=false;
  while (testClass != null && !testClass.equals(GroovyObject.class) && !testClass.equals(Object.class)) {
    try {
      testClass.getDeclaredField(IDENTITY_PROPERTY);
      testClass.getDeclaredField(VERSION_PROPERTY);
      result=true;
      break;
    }
 catch (    SecurityException e) {
    }
catch (    NoSuchFieldException e) {
    }
    testClass=testClass.getSuperclass();
  }
  return result;
}
 

Example 10

From project mob, under directory /com.netappsid.mob/src/com/netappsid/mob/ejb3/tools/.

Source file: JPAHelper.java

  15 
vote

public static Set<Class<?>> buildEntityGraph(Class<?> toInspect) throws IntrospectionException {
  Set<Class<?>> entityClass=new HashSet<Class<?>>();
  if (toInspect.isAnnotationPresent(Entity.class)) {
    entityClass.add(toInspect);
  }
 else {
    throw new IllegalArgumentException("Your root class must be an entity class");
  }
  recurseSuperClass(toInspect.getSuperclass(),entityClass);
  visitProperties(toInspect,entityClass);
  return entityClass;
}
 

Example 11

From project mob, under directory /com.netappsid.mob/src/com/netappsid/mob/ejb3/tools/.

Source file: JPAHelper.java

  15 
vote

/** 
 * @param toInspect
 * @param entitiesClass
 * @throws IntrospectionException
 */
private static void visitProperties(Class<?> toInspect,Set<Class<?>> entitiesClass) throws IntrospectionException {
  BeanInfo beanInfo=Introspector.getBeanInfo(toInspect);
  PropertyDescriptor[] propertyDescriptors=beanInfo.getPropertyDescriptors();
  for (  PropertyDescriptor propertyDescriptor : propertyDescriptors) {
    Method readMethod=propertyDescriptor.getReadMethod();
    if (readMethod == null) {
      continue;
    }
    if (readMethod.isAnnotationPresent(OneToMany.class) || readMethod.isAnnotationPresent(OneToOne.class) || readMethod.isAnnotationPresent(ManyToMany.class)|| readMethod.isAnnotationPresent(ManyToOne.class)) {
      Class<?> propertyType=propertyDescriptor.getPropertyType();
      if (propertyType.isAnnotationPresent(Entity.class) && !entitiesClass.contains(propertyType)) {
        entitiesClass.add(propertyType);
        recurseSuperClass(propertyType,entitiesClass);
        visitProperties(propertyType,entitiesClass);
      }
 else       if (Collection.class.isAssignableFrom(propertyType)) {
        Class<?> entity=(Class<?>)((ParameterizedType)propertyDescriptor.getReadMethod().getGenericReturnType()).getActualTypeArguments()[0];
        if (entity.isAnnotationPresent(Entity.class) && !entitiesClass.contains(entity)) {
          entitiesClass.add(entity);
          recurseSuperClass(entity,entitiesClass);
          visitProperties(entity,entitiesClass);
        }
      }
 else       if (Map.class.isAssignableFrom(propertyType)) {
        Class<?> entity=(Class<?>)((ParameterizedType)propertyDescriptor.getReadMethod().getGenericReturnType()).getActualTypeArguments()[1];
        if (entity.isAnnotationPresent(Entity.class) && !entitiesClass.contains(entity)) {
          entitiesClass.add(entity);
          recurseSuperClass(entity,entitiesClass);
          visitProperties(entity,entitiesClass);
        }
      }
    }
  }
}
 

Example 12

From project openknowledge-cdi-extensions, under directory /openknowledge-cdi-jpa/src/main/java/de/openknowledge/cdi/jpa/.

Source file: JpaExtension.java

  15 
vote

public <T>void processJpaAnnotations(@Observes ProcessAnnotatedType<T> annotatedTypeEvent){
  if (annotatedTypeEvent.getAnnotatedType().isAnnotationPresent(Entity.class) || annotatedTypeEvent.getAnnotatedType().isAnnotationPresent(Embeddable.class)) {
    annotatedTypeEvent.veto();
  }
  AnnotatedType<T> annotatedType=annotatedTypeEvent.getAnnotatedType();
  if (isJpaAnnotationPresent(annotatedType)) {
    annotatedTypeEvent.setAnnotatedType(new JpaAnnotatedType<T>(annotatedType));
  }
}
 

Example 13

From project portal, under directory /portal-core/src/main/java/org/devproof/portal/core/config/factory/.

Source file: DevproofClassPathBeanDefinitionScanner.java

  15 
vote

public DevproofClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry,boolean useDefaultFilters,ModuleConfiguration moduleConfiguration){
  super(registry,useDefaultFilters);
  this.registry=registry;
  this.moduleConfiguration=moduleConfiguration;
  addIncludeFilter(new AnnotationTypeFilter(ModulePage.class));
  addIncludeFilter(new AnnotationTypeFilter(NavigationBox.class));
  addIncludeFilter(new AnnotationTypeFilter(GenericRepository.class));
  addIncludeFilter(new AnnotationTypeFilter(RegisterGenericDataProvider.class));
  addIncludeFilter(new AnnotationTypeFilter(Entity.class));
  addIncludeFilter(new AnnotationTypeFilter(org.hibernate.annotations.Entity.class));
  registerModuleConfigurationAsSingleton();
}
 

Example 14

From project portal, under directory /portal-core/src/main/java/org/devproof/portal/core/config/factory/.

Source file: DevproofClassPathBeanDefinitionScanner.java

  15 
vote

@Override protected void registerBeanDefinition(BeanDefinitionHolder definitionHolder,BeanDefinitionRegistry registry){
  try {
    @SuppressWarnings({"unchecked"}) Class<? extends Page> clazz=(Class<? extends Page>)Class.forName(definitionHolder.getBeanDefinition().getBeanClassName());
    if (clazz.isAnnotationPresent(ModulePage.class)) {
      moduleConfiguration.addPageConfiguration(new PageConfiguration(clazz));
    }
 else     if (clazz.isAnnotationPresent(NavigationBox.class)) {
      moduleConfiguration.addBox(new BoxConfiguration(clazz));
    }
 else     if (clazz.isAnnotationPresent(GenericRepository.class)) {
      BeanDefinitionHolder beanDefinitionHolder=buildGenericRepositoryDefinition(clazz);
      super.registerBeanDefinition(beanDefinitionHolder,registry);
    }
 else     if (clazz.isAnnotationPresent(Entity.class) || clazz.isAnnotationPresent(org.hibernate.annotations.Entity.class)) {
      moduleConfiguration.addEntity(clazz);
      if (clazz.isAnnotationPresent(RegisterGenericDataProvider.class)) {
        BeanDefinitionHolder beanDefinitionHolder=buildGenericDataProviderDefinition(clazz);
        super.registerBeanDefinition(beanDefinitionHolder,registry);
      }
    }
 else {
      super.registerBeanDefinition(definitionHolder,registry);
    }
  }
 catch (  ClassNotFoundException e) {
    logger.fatal(e);
  }
}
 

Example 15

From project querydsl, under directory /querydsl-apt/src/main/java/com/mysema/query/apt/hibernate/.

Source file: HibernateAnnotationProcessor.java

  15 
vote

@Override protected Configuration createConfiguration(RoundEnvironment roundEnv){
  try {
    Class<? extends Annotation> entity=Entity.class;
    Class<? extends Annotation> superType=MappedSuperclass.class;
    Class<? extends Annotation> embeddable=Embeddable.class;
    Class<? extends Annotation> embedded=Embedded.class;
    Class<? extends Annotation> skip=Transient.class;
    return new HibernateConfiguration(roundEnv,processingEnv.getOptions(),entity,superType,embeddable,embedded,skip);
  }
 catch (  ClassNotFoundException e) {
    throw new RuntimeException(e);
  }
}
 

Example 16

From project security, under directory /impl/src/main/java/org/jboss/seam/security/management/picketlink/.

Source file: JpaIdentityStore.java

  15 
vote

protected Object lookupIdentityType(String identityType,EntityManager em){
  Property<Object> typeNameProp=modelProperties.get(PROPERTY_IDENTITY_TYPE_NAME);
  try {
    if (typeNameProp == null)     return identityType;
    final String identTypeEntityAnnotationValue=typeNameProp.getDeclaringClass().getAnnotation(Entity.class).name();
    final String identTypeEntityName=("".equals(identTypeEntityAnnotationValue) ? typeNameProp.getDeclaringClass().getSimpleName() : identTypeEntityAnnotationValue);
    Object val=em.createQuery("select t from " + identTypeEntityName + " t where t."+ typeNameProp.getName()+ " = :identityType").setParameter("identityType",identityType).getSingleResult();
    return val;
  }
 catch (  NoResultException ex) {
    try {
      Object instance=typeNameProp.getDeclaringClass().newInstance();
      typeNameProp.setValue(instance,identityType);
      em.persist(instance);
      return instance;
    }
 catch (    Exception ex2) {
      throw new RuntimeException("Error creating identity type",ex2);
    }
  }
}
 

Example 17

From project security, under directory /impl/src/main/java/org/jboss/seam/security/management/picketlink/.

Source file: JpaIdentityStore.java

  15 
vote

public IdentityObject findIdentityObject(IdentityStoreInvocationContext invocationContext,String id) throws IdentityException {
  try {
    final String identEntityAnnotationValue=identityClass.getAnnotation(Entity.class).name();
    final String identEntityName=("".equals(identEntityAnnotationValue) ? identityClass.getSimpleName() : identEntityAnnotationValue);
    Object identity=getEntityManager(invocationContext).createQuery("select i from " + identEntityName + " i where i."+ modelProperties.get(PROPERTY_IDENTITY_ID).getName()+ " = :id").setParameter("id",id).getSingleResult();
    IdentityObjectType type=modelProperties.containsKey(PROPERTY_IDENTITY_TYPE_NAME) ? new IdentityObjectTypeImpl(modelProperties.get(PROPERTY_IDENTITY_TYPE_NAME).getValue(modelProperties.get(PROPERTY_IDENTITY_TYPE).getValue(identity)).toString()) : new IdentityObjectTypeImpl(modelProperties.get(PROPERTY_IDENTITY_TYPE).getValue(identity).toString());
    return new SimpleIdentityObject(modelProperties.get(PROPERTY_IDENTITY_NAME).getValue(identity).toString(),modelProperties.get(PROPERTY_IDENTITY_ID).getValue(identity).toString(),type);
  }
 catch (  NoResultException ex) {
    return null;
  }
}
 

Example 18

From project spring-data-jpa, under directory /src/main/java/org/springframework/data/jpa/support/.

Source file: ClasspathScanningPersistenceUnitPostProcessor.java

  15 
vote

public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui){
  ClassPathScanningCandidateComponentProvider provider=new ClassPathScanningCandidateComponentProvider(false);
  provider.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
  provider.addIncludeFilter(new AnnotationTypeFilter(MappedSuperclass.class));
  for (  BeanDefinition definition : provider.findCandidateComponents(basePackage)) {
    LOG.debug("Registering classpath-scanned entity %s in persistence unit info!",definition.getBeanClassName());
    pui.addManagedClassName(definition.getBeanClassName());
  }
  for (  String location : scanForMappingFileLocations()) {
    LOG.debug("Registering classpath-scanned entity mapping file in persistence unit info!",location);
    pui.addMappingFileName(location);
  }
}
 

Example 19

From project springfaces, under directory /springfaces/src/main/java/org/springframework/springfaces/selectitems/ui/.

Source file: SelectItemsJpaSupport.java

  15 
vote

@Override public Object getEntityId(Object value){
  try {
    Class<? extends Object> valueClass=value.getClass();
    if (AnnotationUtils.findAnnotation(valueClass,Entity.class) != null) {
      addCacheOfMissing(valueClass);
      Object fieldOrMethod=this.cache.get(valueClass);
      if (fieldOrMethod instanceof Field) {
        return ReflectionUtils.getField((Field)fieldOrMethod,value);
      }
      if (fieldOrMethod instanceof Method) {
        return ReflectionUtils.invokeMethod((Method)fieldOrMethod,value);
      }
    }
  }
 catch (  Exception e) {
  }
  return null;
}
 

Example 20

From project tawus, under directory /tawus-core/src/main/java/com/googlecode/tawus/internal/dataanalyzers/.

Source file: EntityAnalyzer.java

  15 
vote

/** 
 * {@inheritDoc} This selects any collection type which has parameter of typeentity
 */
public String identifyDataType(PropertyAdapter propertyAdapter){
  Class<?> propertyType=propertyAdapter.getType();
  if (propertyType.getAnnotation(Entity.class) != null) {
    return dataType;
  }
  return null;
}
 

Example 21

From project tawus, under directory /tawus-core/src/main/java/com/googlecode/tawus/internal/dataanalyzers/.

Source file: EntityListAnalyzer.java

  15 
vote

/** 
 * {@inheritDoc} This selects any collection type which has parameter of typeentity
 */
public String identifyDataType(PropertyAdapter propertyAdapter){
  Class<?> propertyType=propertyAdapter.getType();
  if (Collection.class.isAssignableFrom(propertyType)) {
    try {
      Type[] type=((ParameterizedType)propertyAdapter.getDeclaringClass().getDeclaredField(propertyAdapter.getName()).getGenericType()).getActualTypeArguments();
      if (type.length == 1 && ((Class<?>)type[0]).getAnnotation(Entity.class) != null) {
        return dataType;
      }
    }
 catch (    NoSuchFieldException nsme) {
      throw new RuntimeException(nsme);
    }
  }
  return null;
}