How do I find entity by their ID in JPA?

In this example you will learn how to find an entity object by its ID using JPA. To find entity by ID we use the EntityManager.find() method and pass the entity class the the entity ID as the parameters.

In the code snippet below the EntityManager required by the ArtistDao will be passed from the main program when the DAO is instantiated. The process of finding the Artist entity is defined in the findById() method in the DAO class. You must pass the ID of the entity to this method.

The findById() method call the EntityManager.find() method to find the entity. If no entity is found, where the artist == null a javax.persistence.EntityNotFoundException will be thrown.

package org.kodejava.example.jpa;

import org.kodejava.example.model.Artist;

import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;

public class ArtistDao {
    private EntityManager manager;

    public ArtistDao(EntityManager manager) {
        this.manager = manager;
    }

    /**
     * Find Artist based on the entity Id.
     *
     * @param artistId the artist Id.
     * @return Artist.
     * @throws EntityNotFoundException when no artist is found.
     */
    public Artist findById(Long artistId) {
        Artist artist = manager.find(Artist.class, artistId);
        if (artist == null) {
            throw new EntityNotFoundException("Can't find Artist for ID "
                    + artistId);
        }
        return artist;
    }
}

To run the DAO class we create a main program in the code snippet below. The steps is create the EntityManagerFactory configured by your persistence.xml file. Create the EntityManager using the factory object. Create the DAO and pass the EntityManager to it. And finally call the findById() method of the DAO class.

package org.kodejava.example.jpa;

import org.kodejava.example.model.Artist;

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

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

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

        ArtistDao dao = new ArtistDao(em);

        //
        // Find an artist with ID = 1 from the database. The entity is
        // exists in the database.
        //
        Artist artist = dao.findById(1L);
        System.out.println("Artist = " + artist);

        try {
            //
            // Find an entity that is not exists in the database will
            // throw an exception.
            //
            artist = dao.findById(100L);
            System.out.println("Artist = " + artist);
        } catch (EntityNotFoundException e) {
            System.out.println("Can't find artist in the database.");
        }
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply