JPA - Delete Employee Example



This chapter takes you through simple example with JPA to delete an Employee record in the MySQL database. We've created Employee.java as entity and persistence.xml in Entity Managers chapter.

Now let's create a service to delete an employee in the database.

Example - Deleting Employee

To Delete an Employee, first we will find the record and then delete it. Here EntityTransaction plays an important role.

The class named DeleteEmployee.java as follows:

DeleteEmployee.java

package com.tutorialspoint.eclipselink.service;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import com.tutorialspoint.eclipselink.entity.Employee;

public class DeleteEmployee {
   public static void main( String[ ] args ) {
   
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      EntityManager entitymanager = emfactory.createEntityManager( );
      entitymanager.getTransaction( ).begin( );
      
      Employee employee = entitymanager.find( Employee.class, 1201 );
      entitymanager.remove( employee );
      entitymanager.getTransaction( ).commit( );
      entitymanager.close( );
      emfactory.close( );
   }
}

Output

After compilation and execution of the above program you will get notifications from Eclipselink library on the console panel of eclipse IDE.

For result, open the MySQL workbench and type the following queries.

use jpadb
select * from employee

The effected database table named employee will have null records.

Advertisements