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 ArtistDaoImpl with a constructor that accept an EntityManager parameter. We provide a couple methods in this DAO such as the save() and getArtist() methods. These methods are for persisting the 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 and its implementation.

package org.kodejava.jpa.dao;

import org.kodejava.jpa.entity.Artist;

import java.util.List;

public interface ArtistDao {
    Artist findById(Long id);

    void save(Artist artist);

    List<Artist> getArtists();
}
package org.kodejava.jpa.dao.impl;

import org.kodejava.jpa.dao.ArtistDao;
import org.kodejava.jpa.entity.Artist;

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

public class ArtistDaoImpl implements ArtistDao {
    private final EntityManager manager;

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

    @Override
    public Artist findById(Long id) {
        return manager.find(Artist.class, id);
    }

    @Override
    public void save(Artist artist) {
        manager.getTransaction().begin();
        manager.persist(artist);
        manager.getTransaction().commit();
    }

    @Override
    @SuppressWarnings(value = "unchecked")
    public List<Artist> getArtists() {
        Query query = manager.createQuery("select a from Artist a", Artist.class);
        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 object we create the EntityManager object which will be passed to the ArtistDaoImpl.

After create an instance of the ArtistDao we insert some artist record to database by calling the dao.save() 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.

<?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.jpa.entity.Artist</class>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/musicdb" />
            <property name="javax.persistence.jdbc.user" value="music" />
            <property name="javax.persistence.jdbc.password" value="s3cr*t" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
        </properties>
    </persistence-unit>

</persistence>
package org.kodejava.jpa;

import org.kodejava.jpa.dao.ArtistDao;
import org.kodejava.jpa.dao.impl.ArtistDaoImpl;
import org.kodejava.jpa.entity.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 ArtistDaoImpl(manager);

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

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

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.