HomeHibernateRemove an Entity from Database using JPA with Hibernate

Remove an Entity from Database using JPA with Hibernate

Remove an Entity :

  • In order to remove an entity, the entity itself must be managed, it means that it is present in the persistence context. This means that the calling application should have already loaded or accessed the entity. The whole point is, before calling EntityManager’s remove(), the instance should be in persistent state.
  • Once an record in the database, Student student = entintyManager.find(Student.class, 1L); this line will retrieve student entity where identifier value is 1. Then entintyManager.remove(student); removes the entity from database.

Note:
To understand more about JPA entity life cycle you can read JPA Entity lifecycle article.

Persistence transition or state change when EntityManager’s find() called :

A removed instance has a persistence identity, is associated with a persistence context and is marked for removal from database.

Technologies Used in all of examples :

  • JPA 2.1
  • Hibernate 5.2.6
  • MySql 8.0
  • Maven 3
  • Spring Tool Suite (STS) 3.9.8
  • Java 1.8

Mapping of Studen.java

@Entity(name="STUDENT")
public class Student {
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO, generator="native")
	@GenericGenerator(name = "native", strategy = "native")
	@Column(name = "ID")
	private Long studentId;
	
	@Column(name = "FNAME")
	private String firstName;
	
	@Column(name = "LNAME")
	private String lastName;
	
	@Column(name = "CONTACT_NO")
	private String contactNo;

       // setters and getters

Removing Entity Code :

public static void main( String[] args )
    {
        EntityManagerFactory emf = null;
        EntityManager entityManager = null;
        EntityTransaction transaction = null;
        
        try{
            emf = Persistence.createEntityManagerFactory("jbd-pu");
            entityManager = emf.createEntityManager();
            transaction = entityManager.getTransaction();
            transaction.begin();
            
            Student student = entityManager.find(Student.class, 2l);
            
            if(student != null)
              entityManager.remove(student);
    
            transaction.commit();
        }catch(Exception e){
            transaction.rollback();
        }finally{
            entityManager.close();
            emf.close();
        }
    }

Output :

INFO - HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select student0_.ID as ID1_0_0_, student0_.CONTACT_NO as CONTACT_2_0_0_, student0_.FNAME as FNAME3_0_0_, student0_.LNAME as LNAME4_0_0_ from STUDENT student0_ where student0_.ID=?
Hibernate: delete from STUDENT where ID=?
INFO - HHH000030: Cleaning up connection pool [jdbc:mysql://localhost:3306/jpa_JBD]

Download Application – JPA-Entity-Remove.zip (10 KB)

LEAVE A REPLY

Please enter your comment!
Please enter your name here