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=[]]

How do I get the primary key of any JPA entity?

If you want to get the primary key of any JPA entity object you can use PersistenceUnitUtil.getIdentifier() method. This method take a single parameter which is the entity object whose identifier to be read. The PersistenceUnitUtil instance can be accessed from the EntityManagerFactory object.

If the entity object contains an identifier the getIdentifier() method will return the identifier as a java.lang.Object. If the entity object doesn’t have an identifier ye it will return null.

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

        Artist artist = manager.find(Artist.class, 1L);
        if (artist != null) {
            Object identifier = 
                    factory.getPersistenceUnitUtil().getIdentifier(artist);
            
            System.out.println("Identifier = " + identifier);
        }
    }
}

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

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

How do I create entity object in JPA?

This example show you a simple example of an entity object used for mapping database table into java object. The entity is a Plain Old Java Object (POJO). The JPA specification doesn’t mandate the class to extends or implements other class or interfaces.

A class which going to be persisted in a database must be annotated with the javax.persistence.Entity annotation (@Entity). As you can see in the Record class below.

By default the mapped table name equals to the class name. But if your table name is different to your class name you can use the @Table annotation. Set the table name using the name attribute of this annotation. This annotation is also located in the javax.persistence package.

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "records")
public class Record implements Serializable {
}

In JPA metadata can be added either in the class fields or using using the getters or setters methods. Choose one option because you cannot mix both of them in the same entity object. Here we will annotate the getters of the class.

To define the primary key of the entity we use the @Id annotation. The @GeneratedValue annotation is used to define how the primary key of the entity should be generated. For example in this example the strategy is defined as GenerationType.AUTO. In MySQL database this is implemented as an auto-increment column.

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }

The fields of the entity by default will be persisted into corresponding fields in the database table. If you don’t want the entity fields to be persisted you must add the @Transient annotation to it. If your entity field name is different with table field you can use the @Column annotation to define the column name and other attributes of the column such as the length, the uniqueness of the field and the not-null attribute.

To define relationship between entity object you can use annotation such as @OneToOne, @OneToMany, @ManyToOne and @ManyToMany. This annotation represent the relationship between database tables in the Java objects.

    @Column(nullable = false, length = 50)
    public String getTitle() {
        return title;
    }

    @Column(name = "release_date")
    public Date getReleaseDate() {
        return releaseDate;
    }

    @ManyToOne
    @JoinColumn(nullable = false)
    public Artist getArtist() {
        return artist;
    }

This is the complete class for the Record entity. This will hold information about music record. This entity have relationship with other entity such the Artist and Label entity.

package org.kodejava.example.model;

import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Entity
@Table(name = "records")
public class Record implements Serializable {
    private static final long serialVersionUID = -5992248672834499258L;

    private Long id;
    private String title;
    private Date releaseDate;
    private Artist artist;
    private Label label;

    private List trackList = new ArrayList<>();

    public Record() {
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }

    @Column(nullable = false, length = 50)
    public String getTitle() {
        return title;
    }

    @Column(name = "release_date")
    public Date getReleaseDate() {
        return releaseDate;
    }

    @ManyToOne
    @JoinColumn(nullable = false)
    public Artist getArtist() {
        return artist;
    }

    @ManyToOne
    @JoinColumn(nullable = false)
    public Label getLabel() {
        return label;
    }

    @OneToMany(mappedBy = "record")
    public List getTrackList() {
        return trackList;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setReleaseDate(Date releaseDate) {
        this.releaseDate = releaseDate;
    }

    public void setArtist(Artist artist) {
        this.artist = artist;
    }

    public void setLabel(Label label) {
        this.label = label;
    }

    public void setTrackList(List trackList) {
        this.trackList = trackList;
    }
}

What is JPA (Java Persistence API)?

JPA is a Java specification for object-relational mapping (ORM) in Java. JPA provide a way to map Java objects to database tables. This allows programmers to manipulate database information directly using Java objects instead of executing database SQL queries.

Developer can choose one of many available JPA specification implementation libraries such as Hibernate, Apache OpenJPA and EclipseLink. EclipseLink is the reference implementation of the JPA specification. In the examples that we are going to provide you in this website, Hibernate library will be used as the persistence provider.

In JPA we model our database tables into a Java objects. This Java objects also called as entity objects. The entity represent a table in database. A single row in a database table will be represented in an instance of the entity. This entity objects hold information about the mapping between objects and database tables. This information or metadata can be defined using an annotation or an XML mapping files.

Here is a simple example of entity object and its metadata information.

package org.kodejava.example.model;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "genres")
public class Genre implements Serializable {
    private static final long serialVersionUID = 6986841075572235403L;

    private Long id;
    private String name;

    public Genre() {
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }

    @Column(nullable = false, length = 50)
    public String getName() {
        return name;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }
}

In the sample entity above we use annotation such as @Entity, @Table, @Id, @GeneratedValue and @Column. These are some annotations that you can use for object mapping.

Besides manipulating database tables using objects JPA also provide a SQL-like queries that can be use to create a static or dynamic query statement.