Hibernate- Hibernate POJO Class Lifecycle

Hibernate POJO Class Lifecycle

In Hibernate POJO class (Persistence class) object will have 3 States

  1. Transient state

  2. Persistent state

  3. Detached state


1. Transient state

  • Whenever an object of a pojo class is created then it will be in the Transient state

  • When the object is in a Transient state it doesn’t represent any row of the database

  • If we modify the data of a pojo class object, when it is in transient state then it doesn’t effect on the database table

2. Persistent state

  • When the object is in persistent state, then it represents one row of the database

  • if the object is in persistent state then it is associated with the unique Session

3. Detached state

  • After Persistent State Object will goes under Dethatched State

  • if we want to move an object from persistent to detached state, we need to do either closing that session or need to clear the cache of the session


package curd;


public class POJOLifeCycle {
public static void main(String[] args) {
     // 1.Load Configuration
     Configuration cfg = new Configuration();
     cfg.configure("hibernate.cfg.xml");
    
     // 2.Create Session
     SessionFactory sf = cfg.buildSessionFactory();
     Session session = sf.openSession();
     
     //======1.Transient State START==========
     EmployeeBo bo = new EmployeeBo();
     bo.setEid(6);
     bo.setName("RAJESH");
     bo.setAddress("NEWYORK");
     //======1.Transient State END==========
     
     
     //======2.Persistent state START==========
     Transaction tx = session.beginTransaction();
     session.save(bo);
     tx.commit(); 
     //======2.Persistent state END==========
     
     
     //========3.Detached State START========  
     session.close();
     bo.setEid(7);
     bo.setName("MADHU");
     bo.setAddress("COLOMBO");
     //========3.Detached State END========	
     sf.close();

  }
}