Category Archives: Hibernate

Dirty checking in Hibernate.

In this it checks that the object state is changed or not. If it is changed, it automatically calls the update method. If commit method is called, In such case state will be updated automatically.
This process is called automatic dirty checking.

SessionFactory objSessionFactory = HibernateUtil.getSessionFactory();
Session objSession = objSessionFactory.openSession();
Transaction objTx = objSession.beginTransaction();
Employee objEmp = (Employee) objSession.load(Employee.class, new Long(101));
objEmp.setName("Rahul");
objTx.comit();
objSession.close();


In this process we have changed employee object and commit the transaction, so it will be automatically updated.

How to make Hibernate Object mutable

Using XML mapping file

<hibernate-mapping>  
  <class name="com.javatpoint.mypackage.Employee" table="emp1000" mutable="false">  
    <id name="id">  
     <generator class="assigned"></generator>  
    </id>            
    <property name="firstName"></property>  
    <property name="lastName"></property>  
   </class>     
</hibernate-mapping>         


Using Annotation: @Mutable

    public class Employee 
    {  
    private int id;  
    private String firstName,lastName;  
      
    public int getId() 
    {  
        return id;  
    }  
    public void setId(int id) 
    {  
        this.id = id;  
    }  
    public String getFirstName() 
    {  
        return firstName;  
    }  
    public void setFirstName(String firstName) 
    {  
        this.firstName = firstName;  
    }  
    public String getLastName() 
    {  
        return lastName;  
    }  
    public void setLastName(String lastName) 
    {  
        this.lastName = lastName;  
    }             
    }  

Hibernate object states

There are three types of Hibernate object states.
1.Transient state:
An object is in transient state if it is just created and not associated with session.
Example :
Employee e1=new Employee();
e1.setId(115);
e1.setFirstName(“Rahul”);
e1.setLastName(“Thakur”);

2.Persistent state:
An object is in persistent state if session is opened and you saved the instance of the object or get the object from the database.
Example :
session.save(e1);

3.Detached state:
An object is in detached state if session is closed. After detached state object come to Persistent state.
Example :
session.close();