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:

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.

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

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.

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:

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