Finding primary key field for Hibernate object

Is it possible for us to find which primary key fields for a Hibernate object programmatically (similar to JPA PersistenceUnitUtil



source to share

3 answers


provides a method called getClassMetadata () to get the metadata object for a class (i.e. ClassMetadata )

To get the name of the properties of an object id 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 instance of a managed object, use ClassMetadata.getIdentifier (object object, SessionImplementor session)

For example: Suppose you have a managed entity instance 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) );




Take a look at PersistentClass

(you get it with configuration.getClassMapping(<classname>)

). There may be useful getIdentifierProperty()

or getKeyClosureIterator()

- depending on your needs.



I realize this question is now over two years old and has already been answered, but it finds between the first 10 Google results for "hibernate get primarykey fields" (and possibly other similar queries), so I think it's important to add that information here.

I was working on a Java system recently and I needed to get the primary key of a table, however all I had was a Hibernate object Configuration

and table name.

While Johanna's answer is very simple and helped me, I found that it did not work as expected for tables with a composite primary key, as only one of the fields that make up the primary key was found.

I dug into properties PersistentClass

and found a way to deal with both cases of primary key (composite and single):

 * Maps a table primary key to a Map<String, String> where the keys are the names of
 * the fields that compose the primary key and the values are the type names of said
 * fields.
 * @param tableName The name of the which for which the primary keys will be gotten
 * @param hibernateConfiguration The Hibernate configuration for the database
 *     IMPORTANT: $tableName must be already mapped in the configuration.
 * @returns A map with the fields names as keys and their types' names as values.
public static Map<String, String> retrievePrimaryKeys(String tableName, Configuration hibernateConfiguration) {

    HashMap<String, String> primaryKeys = new HashMap<>();
    PersistentClass tableMapping = hibernateConfiguration.getClassMapping(tableName);

    Object tableIdentifier =  tableMapping.getIdentifier();

    if(tableIdentifier instanceof SimpleValue) {

        // Whenever the identifier is a SimpleValue, it means that the table has only one PrimaryKey. 
        // At this point, it assumed that the primary key was mapped using the <id> element in the mapping XML file.
        // We iterate over the columns below, because it a safer way of handling this thing.

        SimpleValue tableIdentifierValue = (SimpleValue) tableIdentifier;
        Iterator primaryKeysIterator = tableIdentifierValue.getColumnIterator();

        while(primaryKeysIterator.hasNext()) {
            Column primaryKey = (Column);
            SimpleValue primaryKeyValue = (SimpleValue) primaryKey.getValue();
            primaryKeys.put(primaryKey.getName(), primaryKeyValue.getTypeName());
    else if (tableIdentifier instanceof Component)
        // Whenever the identifier is a Component, it means that the table has a composite primary key.
        // At this point, it assumed that the primary key was mapped using the <composite-id> element in the mapping XML file

        Component identifiers = (Component) tableIdentifier;
        Iterator identifierIterator = identifiers.getPropertyIterator();

        while(identifierIterator.hasNext()) {
            Property identifier = (Property);
            SimpleValue value = (SimpleValue) identifier.getValue();

            primaryKeys.put(identifier.getName(), value.getTypeName());
        // If the program reaches this point, it means that Hibernate hates you and there a third unknown way of declaring and getting a table primary key.

    return primaryKeys;


I must add that Java is not my specialty, as neither is Hibernate, so there might be a better and more concise way to handle this (I hope at least), but I can't seem to find it.



All Articles