Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the primary key field for Hibernate entity

Is it possible for us to find what are the primary key fields for a Hibernate entity programmatically (similar to JPA's PersistenceUnitUtil)?

like image 300
Shyam Avatar asked Mar 21 '12 07:03

Shyam


People also ask

How do you mention primary key in entity class?

With an entity, make sure that you specify the primary key in the class hierarchy. When you specify the primary key, follow the below rules: For a simple (not complex type) primary key, specify @Id in the persistence field or persistence property or specify the key in the O/R mapping file.

Which annotation maps the primary key of an entity?

Name attribute of this annotation is used for specifying the table's column name. @Id : This annotation specifies the primary key of the entity. @GeneratedValue : This annotation specifies the generation strategies for the values of primary keys.

What is primary key in Hibernate?

Identifiers in Hibernate represent the primary key of an entity. This implies the values are unique so that they can identify a specific entity, that they aren't null and that they won't be modified. Hibernate provides a few different ways to define identifiers.


1 Answers

SessionFactory provides an method called getClassMetadata() to get the meta-data object for a class (i.e. ClassMetadata)

To get the name of the identifier properties of an entity , use ClassMetadata.getIdentifierPropertyName()

ClassMetadata employeeMeta =  sessionFactory.getClassMetadata(Employee.class);
System.out.println("Name of the identifier property of the employee entity :" + employeeMeta .getIdentifierPropertyName());

To get the value of the identifier properties for an managed entity instance , use ClassMetadata.getIdentifier(Object entity, SessionImplementor session)

For example : Suppose you have a managed entity instance that is loaded from a session :

List<Employee> employeeList = (List<Employee>)session.createQuery("from Employee where gender ='F'").list();
ClassMetadata employeeMeta = session.getSessionFactory().getClassMetadata(Employee.class);
for (Employee employee : employeeList ) {
    System.out.println("Value of the Primary key:" + employeeMeta.getIdentifier(employee , session) );
}
like image 94
Ken Chan Avatar answered Sep 22 '22 10:09

Ken Chan