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()
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()){
            throw new RuntimeException("id field not found");
        return idProperty;


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


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

Comment are closed.