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

  • Trackback are closed
  • Comments (2)
  1. Or:

    em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(someEntity);

    • Hi laird,
      thanks for feedback :) but this is to get identifier property/field name eg: “id”
      not for the value.

Comment are closed.