Tuesday, April 26, 2016

States of Objects in Hibernate and Hibernate Example 4

Three states of object in hibernate -

  1. Transient
  2. Persistent  
  3. Detached 
public class HibernateTestCRUD {

     public static void main(String[] args) {
          
           //Before object handed over to Hibernate, person object is called Transient Object...
          
           Person person = new Person();
           person.setName("Paras Chawla");
          
         SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
           Session session = sessionFactory.openSession();
           session.beginTransaction();
           // Once object handed over to Hibernate, its called Persistent Object ...
           session.save(person);
          
           // Hibernate after save() tracks the object and save its   last state by itself before close() is called
           person.setName("Name updated and hibernate saving it by its own");
          
           session.getTransaction().commit();
           session.close();
           // Now person object is Detached object and Hibernate is no more tracknig the object
           person.setName("Updated after close()");
          
           // persistent after detached ... by creating new session and updating the object
           session = sessionFactory.openSession();
           session.beginTransaction();
           person.setName("Update after new session created");
           session.update(person);
           session.getTransaction().commit();
          
          
     }
}


Output :
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into Person (name, id) values (?, ?)
Hibernate: update Person set name=? where id=?
Hibernate: update Person set name=? where id=?

Sql > select * from Person

ID|NAME
1|Update after new session created


 1) Object state while Create


2) Object state while deleting

 3) Object state while reading 




4) Session used in tracking object once object is persisted from transient.


No comments:

Post a Comment