How do I delete entity object in JPA?

The following code example show you how to delete or remove entity object from database using JPA. The first class that we are going to create is ArtistDao. This DAO class handles the delete process either by the entity Id or by the entity object itself. We define the delete process in deleteArtistById(Long artistId) and deleteArtist(Artist artist) methods.

In those methods we call the EntityManager.remove() method. This method of EntityManager will taking care of removing the entity object from our database. Let’s see the DAO code below:

package org.kodejava.example.jpa;

import org.kodejava.example.model.Artist;

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

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

    /**
     * Create a new artist record in the database.
     *
     * @param artist Artist to be created.
     * @return the ID of saved Artist.
     */
    public void createArtist(Artist artist) {
        manager.getTransaction().begin();
        manager.persist(artist);
        manager.getTransaction().commit();
    }

    /**
     * Get Artists from database.
     *
     * @return a list of artist.
     */
    @SuppressWarnings("unchecked")
    public List getArtists() {
        Query query = manager.createQuery("select a from Artist a");
        return query.getResultList();
    }

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

    /**
     * Delete artist by their Id.
     *
     * @param artistId the artist Id.
     */
    public void deleteArtistById(Long artistId) {
        Artist artist = manager.find(Artist.class, artistId);
        if (artist != null) {
            manager.getTransaction().begin();
            manager.remove(artist);
            manager.getTransaction().commit();
        }
    }

    /**
     * Delete artist entity.
     *
     * @param artist the object to be deleted.
     */
    public void deleteArtist(Artist artist) {
        manager.getTransaction().begin();
        manager.remove(artist);
        manager.getTransaction().commit();
    }
}

After defining the delete methods in the ArtistDao class we create a simple program to demonstrate both of them. In this program we start by create the EntityManagerFactory object from the defined persistence unit in the persistence.xml file. Then we create the EntityManager object and we pass it to our ArtistDao object. And then we call the delete methods to remove entity from the database.

To show you the result of the delete process we print out the artist data before and after the delete method is called.

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 EntityRemoveDemo {
    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();

        ArtistDao dao = new ArtistDao(manager);
        System.out.println("Before Delete:");
        printArtists(dao.getArtists());

        //
        // Remove artist with Id = 1.
        //
        dao.deleteArtistById(1L);

        //
        // Remove artist with Id = 2.
        //
        Artist artist = dao.findById(2L);
        dao.deleteArtist(artist);

        System.out.println("After Delete:");
        printArtists(dao.getArtists());
    }

    private static void printArtists(List artists) {
        for (Artist artist : artists) {
            System.out.println("Artist = " + artist);
        }
    }
}

Here is the result of our code snippet. It shows the number of records before and after the delete process.

Before Delete:
Artist = [email protected][id=1,name=Bryan Adams,records=[]]
Artist = [email protected][id=3,name=Metallica,records=[]]
Artist = [email protected][id=2,name=Mr. Big,records=[]]
After Delete:
Artist = [email protected][id=3,name=Metallica,records=[]]
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