Retrieving Id field from JPA and Hibernate
quick code snippet to get the identifier field name for a given entity class from both hibernate and JPA 2.0 APIs.
for hibernate
public String getIdProperty(Class entityClass) {
String idProperty=sessionAccessor.getSessionFactory()
.getClassMetadata(entityClass)
.getIdentifierPropertyName();
return idProperty;
}
for JPA 2.0 metamodel API this method or to get value of id field see comment below
public String getIdProperty(Class entityClass) {
String idProperty;
Metamodel metamodel = getEntityManager().getMetamodel();
EntityType entity = metamodel.entity(entityClass);
Set<SingularAttribute> singularAttributes = entity.getSingularAttributes();
for (SingularAttribute singularAttribute : singularAttributes) {
if (singularAttribute.isId()){
idProperty=singularAttribute.getName();
break;
}
}
if(idProperty==null)
throw new RuntimeException("id field not found");
return idProperty;
}
to


Or:
em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(someEntity);
Hi laird,
but this is to get identifier property/field name eg: “id”
thanks for feedback
not for the value.