Tuesday, 22 May 2018

What Are the Different States of an Entity in Hibernate?

       In Hibernate, every entity object goes through different states during its lifecycle. These states define how Hibernate manages the entity and whether it is associated with a database record or a Hibernate session.

Understanding the different entity states is essential because it helps developers manage data efficiently and avoid common issues such as LazyInitializationException, duplicate inserts, and unnecessary database operations.

Hibernate defines four main entity states:

  • Transient
  • Persistent
  • Detached

             1) Transient
       
       Whenever we create a new entity object, it is in the Transient state. At this stage, any modifications made to the object's state do not affect the database because the object is not yet associated with a Hibernate session.


             2)  Persistent 
          
       Whenever an entity object is associated with a Hibernate session, it is said to be in the Persistent state. Any changes made to the object's state are automatically synchronized with the database when the transaction is committed.
     
            3) Detached

     Whenever an entity object is removed from the Hibernate session, it enters the Detached state. Any modifications made to a detached object are not reflected in the database because it is no longer associated with the session.

Example:--

package com.test;
public class Student {
 
      private int studentId;
      private String studentName;
      private String standard;
 
      public int getStudentId() {
           return studentId;
      }
      public void setStudentId(int studentId) {
           this.studentId = studentId;
      }
      public String getStudentName() {
           return studentName;
      }
      public void setStudentName(String studentName) {
           this.studentName = studentName;
      }
      public String getStandard() {
           return standard;
      }
      public void setStandard(String standard) {
           this.standard = standard;
      }
}


class EntityState {

    public static void main(String[]args) {

         SessionnFactory factory=new Configuration().configure("hibernate.cfg.xml").buildSessionFactpry();
         Sessiion session1=factory.openSession(); 
         
         // Entity bean in Transient state.
         Student s = new Student();    
         s.setStudentName("Mahesh");
         s.setStudentId(20);
         s.setStandard(7);
         
         Transaction tx1=session1.beginTransaction();
         // Entity in Persistent State.
         session1.save(s);
         s.setStandard(8);
         tx1.commit();
         session1.close(); 

         // Now s becomes detached, this is detached state
         s.setStandard(8);; //  Will not effect in db
    
    }
} 
  
Thank you for visiting the blog.

No comments:

Post a Comment