Retrieving Id field from JPA and Hibernate

altuure
altuure
Oct 25, 2010 · 1 min read

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

altuure

Continous Developer Blog

altuure

Continous Developer Blog

altuure

Written by

altuure

#expat #amsterdam #cycling

altuure

Continous Developer Blog