How do I get the primary key of any JPA entity?

If you want to get the primary key of any JPA entity object you can use PersistenceUnitUtil.getIdentifier() method. This method take a single parameter which is the entity object whose identifier to be read. The PersistenceUnitUtil instance can be accessed from the EntityManagerFactory object.

If the entity object contains an identifier the getIdentifier() method will return the identifier as a java.lang.Object. If the entity object does not have an identifier ye it will return null.

package org.kodejava.jpa;

import org.kodejava.jpa.entity.Artist;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class GetEntityIdDemo {
    public static final String PERSISTENCE_UNIT_NAME = "music";

    public static void main(String[] args) {
        EntityManagerFactory factory =
                Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        EntityManager manager = factory.createEntityManager();

        // Get object identifier of an exists entity.
        Artist artist = manager.find(Artist.class, 1L);
        if (artist != null) {
            Object identifier =
                    factory.getPersistenceUnitUtil().getIdentifier(artist);

            System.out.println("Identifier = " + identifier);
        }

        // Get object identifier of a newly inserted entity.
        Artist newArtist = new Artist();
        newArtist.setName("Bon Jovi");

        manager.getTransaction().begin();
        manager.persist(newArtist);
        manager.getTransaction().commit();

        Object identifier =
                factory.getPersistenceUnitUtil().getIdentifier(newArtist);
        System.out.println("Identifier = " + identifier);
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.persistence</groupId>
        <artifactId>javax.persistence-api</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.