Java Code Examples for javax.persistence.Id
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 b3log-latke, under directory /latke/src/main/java/org/b3log/latke/repository/jpa/.
Source file: EntityManagerImpl.java

/** * Converts the specified entity to a json object. * @param entity the specified entity * @return json object * @throws Exception exception */ private JSONObject toJSONObject(final Object entity) throws Exception { final JSONObject ret=new JSONObject(); final Class<? extends Object> clazz=entity.getClass(); final MetaEntity metaEntity=Entities.getMetaEntity(clazz); final Map<String,Field> fields=metaEntity.getFields(); for ( final Map.Entry<String,Field> entityField : fields.entrySet()) { final String fieldName=entityField.getKey(); final Field field=entityField.getValue(); final Class<?> fieldType=field.getType(); field.setAccessible(true); final Object fieldValue=field.get(entity); if (field.isAnnotationPresent(Id.class)) { if (null != fieldValue) { ret.put(Keys.OBJECT_ID,fieldValue); } continue; } if (fieldType.isPrimitive() || String.class.equals(fieldType)) { ret.put(fieldName,fieldValue); } } return ret; }
Example 2
From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/repository/jpa/.
Source file: MetaEntity.java

/** * Constructs a meta entity with the specified entity class. * @param entityClass the specified entity class */ public MetaEntity(final Class<?> entityClass){ LOGGER.log(Level.FINER,"Analysing an entity scheme...."); if (!EntityClassCheckers.isValid(entityClass)) { throw new IllegalArgumentException("The specified class is not a valid entity class"); } this.entityClass=entityClass; final String entityClassName=entityClass.getSimpleName(); repositoryName=entityClassName.substring(0,1).toLowerCase() + entityClassName.substring(1); LOGGER.log(Level.FINER,"Entity[classSimpleName={0}] to repository[name={1}]",new Object[]{entityClass.getSimpleName(),repositoryName}); final Field[] allFields=entityClass.getDeclaredFields(); for (int i=0; i < allFields.length; i++) { final Field field=allFields[i]; final Class<?> fieldClass=field.getType(); if (field.isAnnotationPresent(Id.class)) { fields.put(Keys.OBJECT_ID,field); continue; } if (fieldClass.isPrimitive() || String.class.equals(fieldClass)) { fields.put(field.getName(),field); continue; } if (field.isAnnotationPresent(OneToOne.class) || field.isAnnotationPresent(ManyToOne.class)) { fields.put(field.getName() + "Id",field); continue; } if (field.isAnnotationPresent(ManyToMany.class)) { final String many2ManyReposName=fieldClass.getSimpleName() + '_' + entityClass.getSimpleName(); Relationships.addManyToManyRepositoryName(many2ManyReposName); } } Entities.addMetaEntity(this); }
Example 3
From project Core_2, under directory /javaee-impl/src/main/java/org/jboss/forge/spec/javaee/jpa/.
Source file: EntityPlugin.java

@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 4
From project Core_2, under directory /javaee-impl/src/main/java/org/jboss/forge/spec/javaee/rest/.
Source file: RestPlugin.java

private String resolveIdType(JavaClass entity){ for ( Member<JavaClass,?> member : entity.getMembers()) { if (member.hasAnnotation(Id.class)) { if (member instanceof Method) { return ((Method<?>)member).getReturnType(); } if (member instanceof Field) { return ((Field<?>)member).getType(); } } } return "Object"; }
Example 5
From project Core_2, under directory /scaffold-faces/src/main/java/org/jboss/forge/scaffold/faces/.
Source file: FacesScaffold.java

private void setPrimaryKeyMetaData(Map<Object,Object> context,final JavaClass entity){ String pkName="id"; String pkType="Long"; String nullablePkType="Long"; for ( Member<JavaClass,?> m : entity.getMembers()) { if (m.hasAnnotation(Id.class)) { if (m instanceof Field) { Field<?> field=(Field<?>)m; pkName=field.getName(); pkType=field.getType(); nullablePkType=field.getType(); break; } Method<?> method=(Method<?>)m; pkName=method.getName().substring(3); if (method.getName().startsWith("get")) { pkType=method.getReturnType(); } else { pkType=method.getParameters().get(0).getType(); } break; } } if ("int".equals(pkType)) { nullablePkType=Integer.class.getSimpleName(); } else if ("short".equals(pkType)) { nullablePkType=Short.class.getSimpleName(); } else if ("byte".equals(pkType)) { nullablePkType=Byte.class.getSimpleName(); } context.put("primaryKey",pkName); context.put("primaryKeyCC",StringUtils.capitalize(pkName)); context.put("primaryKeyType",pkType); context.put("nullablePrimaryKeyType",nullablePkType); }
Example 6
From project Core_2, under directory /scaffold-faces/src/main/java/org/jboss/forge/scaffold/faces/metawidget/inspector/.
Source file: ForgeInspector.java

@Override protected Map<String,String> inspectProperty(Property property) throws Exception { Map<String,String> attributes=CollectionUtils.newHashMap(); if (property.isAnnotationPresent(OneToOne.class) || property.isAnnotationPresent(Embedded.class)) { attributes.put(ONE_TO_ONE,TRUE); } if (property.isAnnotationPresent(ManyToOne.class)) { attributes.put(FACES_LOOKUP,StaticFacesUtils.wrapExpression(StringUtils.decapitalize(ClassUtils.getSimpleName(property.getType())) + "Bean.all")); attributes.put(FACES_CONVERTER_ID,StaticFacesUtils.wrapExpression(StringUtils.decapitalize(ClassUtils.getSimpleName(property.getType())) + "Bean.converter")); for ( Property reverseProperty : getProperties(property.getType()).values()) { if (reverseProperty.isAnnotationPresent(Id.class)) { attributes.put(REVERSE_PRIMARY_KEY,reverseProperty.getName()); break; } } } if (property.isAnnotationPresent(OneToMany.class) || property.isAnnotationPresent(ManyToMany.class)) { attributes.put(N_TO_MANY,TRUE); } if (property instanceof ForgeProperty) { List<EnumConstant<JavaEnum>> enumConstants=((ForgeProperty)property).getEnumConstants(); if (enumConstants != null) { List<String> lookup=CollectionUtils.newArrayList(); for ( EnumConstant<JavaEnum> anEnum : enumConstants) { lookup.add(anEnum.getName()); } attributes.put(LOOKUP,CollectionUtils.toString(lookup)); } } if (property.isAnnotationPresent(Id.class)) { attributes.put(PRIMARY_KEY,TRUE); } return attributes; }
Example 7
From project Core_2, under directory /scaffold-faces/src/test/java/org/jboss/forge/scaffold/faces/.
Source file: PrimaryKeyFacesScaffoldTest.java

@SuppressWarnings("unchecked") private void generateLegacyEntities(Project project) throws FileNotFoundException { JavaSourceFacet java=project.getFacet(JavaSourceFacet.class); JavaClass javaClass=JavaParser.create(JavaClass.class).setPackage("com.test.model").setName("State").setPublic().addAnnotation(Entity.class).getOrigin().addInterface(Serializable.class); String idName="stateId"; Field<JavaClass> id=javaClass.addField("private String " + idName + " = null;"); id.addAnnotation(Id.class); id.addAnnotation(GeneratedValue.class).setEnumValue("strategy",GenerationType.AUTO); Refactory.createGetterAndSetter(javaClass,id); Refactory.createToStringFromFields(javaClass,id); Refactory.createHashCodeAndEquals(javaClass); java.saveJavaSource(javaClass); javaClass=JavaParser.create(JavaClass.class).setPackage("com.test.model").setName("Parent").setPublic().addAnnotation(Entity.class).getOrigin().addInterface(Serializable.class); idName="parentId"; id=javaClass.addField("private String " + idName + " = null;"); id.addAnnotation(Id.class); id.addAnnotation(GeneratedValue.class).setEnumValue("strategy",GenerationType.AUTO); id.addAnnotation(Column.class).setStringValue("name",idName).setLiteralValue("updatable","false").setLiteralValue("nullable","false"); Refactory.createGetterAndSetter(javaClass,id); Field<JavaClass> name=javaClass.addField("private String name = null;"); name.addAnnotation(Column.class).setLiteralValue("nullable","false"); Refactory.createGetterAndSetter(javaClass,name); Field<JavaClass> state=javaClass.addField("private State state = null;"); state.addAnnotation(ManyToOne.class).setLiteralValue("optional","false"); Refactory.createGetterAndSetter(javaClass,state); Refactory.createToStringFromFields(javaClass,id); Refactory.createHashCodeAndEquals(javaClass); java.saveJavaSource(javaClass); }
Example 8
From project Easy-Cassandra, under directory /src/main/java/org/easycassandra/persistence/.
Source file: ColumnUtil.java

/** * create columns based on annotations in Easy-Cassandra * @param object - the object viewed * @return - List of the Column */ public static List<Column> getColumns(Object object){ Long timeStamp=System.currentTimeMillis(); List<Column> columns=new ArrayList<Column>(); List<Field> fields=listFields(object.getClass()); for ( Field field : fields) { if (field.getName().equals("serialVersionUID") || field.getAnnotation(Id.class) != null || ReflectionUtil.getMethod(object,field) == null) { continue; } if (ColumnUtil.isNormalField(field)) { Column column=makeColumn(timeStamp,ColumnUtil.getColumnName(field),object,field); addColumn(columns,column); } else if (ColumnUtil.isEmbeddedField(field)) { if (ReflectionUtil.getMethod(object,field) != null) { columns.addAll(getColumns(ReflectionUtil.getMethod(object,field))); } } else if (ColumnUtil.isEnumField(field)) { Column column=doEnumColumn(object,timeStamp,field); addColumn(columns,column); } } return columns; }
Example 9
From project Easy-Cassandra, under directory /src/test/java/org/easycassandra/annotations/.
Source file: AnnotationsTest.java

@Test public void existKeyValueTest(){ boolean existKeyValue=false; for ( Field field : Person.class.getDeclaredFields()) { if (field.getAnnotation(Id.class) != null) { existKeyValue=true; break; } } Assert.assertTrue(existKeyValue); }
Example 10
From project Easy-Cassandra, under directory /src/test/java/org/easycassandra/annotations/.
Source file: AnnotationsTest.java

@Test public void retrieveKeyValueTest(){ for ( Field field : Person.class.getDeclaredFields()) { if (field.getAnnotation(Id.class) != null) { Assert.assertTrue(true); } } Assert.assertFalse(false); }
Example 11
From project harmony, under directory /harmony.idb/src/main/java/org/opennaas/extensions/idb/database/hibernate/.
Source file: TNAPrefix.java

/** * @return prefix of the domain */ @Id public String getPrefix(){ if (this.prefix == null) { this.prefix=""; } return this.prefix; }
Example 12
From project orientdb, under directory /src/play/modules/orientdb/.
Source file: OModelLoader.java

@SuppressWarnings("rawtypes") Field keyField(){ Class c=clazz; try { while (!c.equals(Object.class)) { for ( Field field : c.getDeclaredFields()) { if (field.isAnnotationPresent(Id.class) || field.isAnnotationPresent(OId.class)) { field.setAccessible(true); return field; } } c=c.getSuperclass(); } } catch ( Exception e) { throw new UnexpectedException("Error while determining the object @Id for an object of type " + clazz); } throw new UnexpectedException("Cannot get the object @Id for an object of type " + clazz); }
Example 13
From project plugin-spring-mvc, under directory /src/main/java/org/jboss/forge/scaffold/spring/metawidget/inspector/.
Source file: ForgeInspector.java

@Override protected Map<String,String> inspectProperty(Property property) throws Exception { Map<String,String> attributes=CollectionUtils.newHashMap(); if (property.isAnnotationPresent(OneToOne.class) || property.isAnnotationPresent(Embedded.class)) { attributes.put(ONE_TO_ONE,TRUE); } if (property.isAnnotationPresent(ManyToOne.class)) { attributes.put(SPRING_LOOKUP,StaticFacesUtils.wrapExpression(StringUtils.decapitalize(ClassUtils.getSimpleName(property.getType())))); for ( Property reverseProperty : getProperties(property.getType()).values()) { if (reverseProperty.isAnnotationPresent(Id.class)) { attributes.put(REVERSE_PRIMARY_KEY,reverseProperty.getName()); break; } } } if (property.isAnnotationPresent(OneToMany.class) || property.isAnnotationPresent(ManyToMany.class)) { attributes.put(N_TO_MANY,TRUE); } if (property instanceof ForgeProperty) { List<EnumConstant<JavaEnum>> enumConstants=((ForgeProperty)property).getEnumConstants(); if (enumConstants != null) { List<String> lookup=CollectionUtils.newArrayList(); for ( EnumConstant<JavaEnum> anEnum : enumConstants) { lookup.add(anEnum.getName()); } attributes.put(LOOKUP,CollectionUtils.toString(lookup)); } } if (property.isAnnotationPresent(Id.class)) { attributes.put(PRIMARY_KEY,TRUE); } return attributes; }
Example 14
From project security, under directory /impl/src/main/java/org/jboss/seam/security/management/picketlink/.
Source file: JpaIdentityStore.java

protected void configureIdentityId() throws IdentityException { List<Property<Object>> props=PropertyQueries.createQuery(identityClass).addCriteria(new AnnotatedPropertyCriteria(Id.class)).getResultList(); if (props.size() == 1) { modelProperties.put(PROPERTY_IDENTITY_ID,props.get(0)); } else { throw new IdentityException("Error initializing JpaIdentityStore - no Identity ID found."); } }
Example 15
From project springfaces, under directory /springfaces/src/main/java/org/springframework/springfaces/selectitems/ui/.
Source file: SelectItemsJpaSupport.java

private void addIdFieldToCache(final Class<?> valueClass){ ReflectionUtils.doWithFields(valueClass,new FieldCallback(){ public void doWith( Field field) throws IllegalArgumentException, IllegalAccessException { if (field.getAnnotation(Id.class) != null) { field.setAccessible(true); HasJpa.this.cache.put(valueClass,field); } } } ); }
Example 16
From project springfaces, under directory /springfaces/src/main/java/org/springframework/springfaces/selectitems/ui/.
Source file: SelectItemsJpaSupport.java

private void addIdMethodToCache(final Class<?> valueClass){ ReflectionUtils.doWithMethods(valueClass,new MethodCallback(){ public void doWith( Method method) throws IllegalArgumentException, IllegalAccessException { if (AnnotationUtils.getAnnotation(method,Id.class) != null) { method.setAccessible(true); HasJpa.this.cache.put(valueClass,method); } } } ); }
Example 17
From project vaadin, under directory /impl/src/main/java/br/gov/frameworkdemoiselle/vaadin/template/.
Source file: AbstractCrudPresenter.java

@SuppressWarnings("unchecked") private I getIdFieldValue(E object){ I result=null; Field[] fields=Reflections.getNonStaticDeclaredFields(object.getClass()); for ( Field field : fields) { if (field.isAnnotationPresent(Id.class)) { result=(I)Reflections.getFieldValue(field,object); break; } } return result; }