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 doesn’t have an identifier ye it will return null.

package org.kodejava.example.jpa;

import org.kodejava.example.model.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 =
        EntityManager manager = factory.createEntityManager();

        Artist artist = manager.find(Artist.class, 1L);
        if (artist != null) {
            Object identifier = 
            System.out.println("Identifier = " + identifier);

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🙂.

Leave a Reply

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