How do I update entity object using JPA?

In this example you will learn how to update an entity object in JPA. We use the EntityManager.merge() method to update an entity. This method takes the entity to be saved as the parameter and return the merged entity back as the result.

You can see a simple example to the code snippet below:

package org.kodejava.example.jpa;

import org.kodejava.example.model.Artist;

import javax.persistence.EntityManager;

public class ArtistDao {
    private EntityManager manager;

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

    /**
     * Update Artist information.
     *
     * @param artist an Artist to be updated.
     */
    public void updateArtist(Artist artist) {
        manager.getTransaction().begin();
        manager.merge(artist);
        manager.getTransaction().commit();
    }
}

And here a main program for running the ArtistDao class to update the artist data in the database.

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 EntityUpdateDemo {
    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);
        Artist artist = dao.findById(1L);
        System.out.println("Artist = " + artist);

        artist.setName("The New Artist Name");
        dao.updateArtist(artist);

        artist = dao.findById(artist.getId());
        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