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