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.");
        }
    }
}

How do I persist entity to database in JPA?

In this example you are going to learn how to persist or save an entity object to database table using JPA. We are going to create a data access object (DAO) for persisting an Artist entity.

We create a class called ArtistDao with a constructor that accept an EntityManager parameter. We provide a couple methods in this DAO such as the createArtist() and getArtist() methods. This method is for persisting entity and retrieve a collection of entities from the database.

To persist object to database we call the EntityManager.persist() method with the entity object to be saved as the parameter. We also have to begin and commit the transaction before and after we call the persist() method. Here is the code for our DAO.

package org.kodejava.example.jpa;

import org.kodejava.example.model.Artist;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

public class ArtistDao {
    private EntityManager manager;

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

    public Artist findById(Long artistId) {
        return manager.find(Artist.class, artistId);
    }

    public void createArtist(Artist artist) {
        manager.getTransaction().begin();
        manager.persist(artist);
        manager.getTransaction().commit();
    }

    @SuppressWarnings("unchecked")
    public List getArtists() {
        Query query = manager.createQuery("select a from Artist a");
        return query.getResultList();
    }
}

To demonstrate the DAO we create a simple program as you can see below. The program start by creating the EntityManagerFactory configured by the persistence unit defined in the persistence.xml file. From the factory we create the EntityManager object which will be passed to the ArtistDao.

After create an instance of the ArtistDao we insert some artist record to database by calling the dao.createArtist() method. To check that the data successfully stored in the database we call the dao.getArtists() to read the data back from the database and print it out to the screen.

package org.kodejava.example.jpa;

import org.kodejava.example.model.Artist;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.List;

public class EntityPersistDemo {
    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();

        String[] artistNames = {"Bryan Adams", "Mr. Big", "Metallica"};

        ArtistDao dao = new ArtistDao(manager);

        for (String name : artistNames) {
            Artist artist = new Artist();
            artist.setName(name);
            dao.createArtist(artist);
        }

        List artistList = dao.getArtists();
        for (Artist artist : artistList) {
            System.out.println("artist = " + artist);
        }
    }
}

How do I create JPA EntityManagerFactory?

In this code snippet you will learn how to create JPA EntityManagerFactory. This factory enable you to create the EntityManager which will be used to execute the JPA command to manipulate the database tables.

To create the EntityManagerFactory you need to create to persistence.xml file first. The file is where you configure the JPA. This file must be placed inside the META-INF directory in your program working directory.

Here is an example of the persistence.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">

    <persistence-unit name="music" transaction-type="RESOURCE_LOCAL">
        <class>org.kodejava.example.model.Artist</class>
        <class>org.kodejava.example.model.Genre</class>
        <class>org.kodejava.example.model.Label</class>
        <class>org.kodejava.example.model.Record</class>
        <class>org.kodejava.example.model.Review</class>
        <class>org.kodejava.example.model.Reviewer</class>
        <class>org.kodejava.example.model.Track</class>
        <properties>
            <property name="javax.persistence.jdbc.driver"
                      value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url"
                      value="jdbc:mysql://localhost/musicdb"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value=""/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.hbm2ddl.auto" value="create"/>
        </properties>
    </persistence-unit>

</persistence>

The persistence unit defined in the persistence.xml file contains a set of entities object. We also define some properties related to the database connections including the JDBC driver class, JDBC url, the username and password for opening the connection to database.

After defining the persistence.xml file we’ll create a simple program to create the EntityManagerFactory. To create the factory we can use the javax.persistence.Persistence class createEntityManagerFactory() method and pass the persistence unit name as the parameter. In this example the persistence unit name is music as can be seen in the persistence.xml file.

After we have the factory object created we can then create an EntityManager by calling the createEntityManager() of the factory object. Let’s see the code snippet below.

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 EntityManagerFactoryExample {
    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();
        
        //
        // Do something with the entity manager.
        //
        Artist artist = manager.find(Artist.class, 1L);
        System.out.println("artist = " + artist);
    }
}