Wednesday, December 31, 2014

Explain about Hibernate Object Life Cycle?

In hibernate object life cycle, mainly consists of four states. They are 
  1. Transient State, 
  2. Persistent State, 
  3. Detached State and 
  4. Removed State.
Hibernate Object Life Cycle

1. New or Transient State:
When ever an object of a POJO class is Created(instantiated) using the new operator then it will be in the Transient state; this object is not associated with any Hibernate Session.
For example,
Employee employee = new Employee("Ranga", 27, 30998); // Transient
When we call delete() on persistent object then it also moves to transient state.
session.delete(employee); 
This object don’t have any association with any database table row. In other words any modification in data of transient state object doesn't have any impact on the database table. so their state is lost as soon as they’re no longer referenced by any other object.
Note: Transient objects exist in heap memory.
Transient state will be happened two scenarios:
  1. First where the objects are created by application but not connected to a session, and 
  2. Second the objects are created by a closed session.
Converting Transient State to Persistence State:
  • By saving the that object
    • session.save()
    • session.persist()
    • session.saveOrUpdate()
  • By loading that object from database
    • session.load()
    • session.get(),
    • session.byId()
    • session.byNaturalId() etc..
2. Persistent or Managed State:
In order to convert or move an object from Transient to Persistent, there are two ways.
  1. Saving the object to the database using session
  2. Loading the object from the database using session
In this state object known to the hibernate and represent a one row in the database. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes.
Different ways to Save an Object:
Hibernate supports the different ways to save an object to the database. They are
  • session.save()
  • session.saveOrUpdate()
  • session.persist()
For example,
Employee employee = new Employee("Ranga", 27, 30998); // Transient
session.save(employee); // persitent

Different Ways to Load an Object:
Hibernate supports the different ways to load an object from the database. Few of them are
  • session.get()
  • session.load()
  • session.byId()
  • session.byNaturalId() etc...
For example,
Employee employee = session.get(Employee.class, 1); // here employee object is associated   with session. So employee object state is Persistent.
Persistent State
We can covert the object from persistent state to detached state by clearing the cache of the session or close the session using evict(), clear() and close() methods.

Converting Persistent State to Detached State:
  • session.evict();
  • session.clear();
  • session.close();
3. Detached State:
In order to convert or move an object from Persistence to Detached State, we need to clear the cache of the session or close the session by using following methods.
  • session.evict();  - clear particular object from the cache
  • session.clear();  - clears all objects from the cache
  • session.close(); 
Employee employee = new Employee("Ranga", 27, 30998); // Transient
session.save(employee); // persitent
session.close(); // here employee state is detached because currently it is not associated with session.
Detached State
Changes made in this object does not reflect to the database. But we can change the state to persistent by calling following methods on detached object.
  • session.update()
  • session.merge()
  • session.saveOrUpdate()
Converting Detached State to Persistent State:
  • session.update()
  • session.merge()
  • session.saveOrUpdate()
4. Removed State:
This is last state in the hibernate object life cycle. A persistent object is considered to be in the removed state when a delete() operation is called on it. Note that Once you've deleted an object and moved to the “removed” state, you should no longer use that particular object for any reason.
For example:
session.delete(employee);
Removed State
Example:
package com.varasofttech.client;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.varasofttech.pojo.Employee;
import com.varasofttech.util.HibernateUtil;

public class Application {
public static void main(String[] args) {

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();

// Hibernate Object Life Cycle

// New or Transient State begin
Employee employee = new Employee("Ranga", 27, 30998);
// New or Transient State end

System.out.println("Session Info in Transient State : ");
System.out.println(session);

// Persistent or Managed State begin
Transaction transaction = session.beginTransaction();
session.save(employee);
transaction.commit();
// Persistent or Managed State end

System.out.println("Session Info in Persistent State : ");
System.out.println(session);

// Detached State begin
session.evict(employee);
// Detached State end

System.out.println("Session Info in Detached State : ");
System.out.println(session);

// Persistent State begin
transaction = session.beginTransaction();
employee.setName("Ranga Reddy");
employee.setAge(27);

session.saveOrUpdate(employee);
transaction.commit();
// Persistent State end

System.out.println("Session Info in Persistent State : ");
System.out.println(session);

// Removed State begin
session.delete(employee);
// Removed State end

System.out.println("Session Info in Removed State : ");
System.out.println(session);

sessionFactory.close();
}

}

Output:

Session Info in Transient State : 
SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@59505b48 updates=org.hibernate.engine.spi.ExecutableList@4efac082 deletions=org.hibernate.engine.spi.ExecutableList@6bd61f98 orphanRemovals=org.hibernate.engine.spi.ExecutableList@48aca48b collectionCreations=org.hibernate.engine.spi.ExecutableList@13fd2ccd collectionRemovals=org.hibernate.engine.spi.ExecutableList@b9b00e0 collectionUpdates=org.hibernate.engine.spi.ExecutableList@506ae4d4 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@7d4f9aae unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])

Hibernate: select max(e_id) from employees
Hibernate: insert into employees (e_name, e_age, e_salary, e_id) values (?, ?, ?, ?)

Session Info in Persistent State :
SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.varasofttech.pojo.Employee#9]],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@59505b48 updates=org.hibernate.engine.spi.ExecutableList@4efac082 deletions=org.hibernate.engine.spi.ExecutableList@6bd61f98 orphanRemovals=org.hibernate.engine.spi.ExecutableList@48aca48b collectionCreations=org.hibernate.engine.spi.ExecutableList@13fd2ccd collectionRemovals=org.hibernate.engine.spi.ExecutableList@b9b00e0 collectionUpdates=org.hibernate.engine.spi.ExecutableList@506ae4d4 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@7d4f9aae unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])

Session Info in Detached State :
SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@59505b48 updates=org.hibernate.engine.spi.ExecutableList@4efac082 deletions=org.hibernate.engine.spi.ExecutableList@6bd61f98 orphanRemovals=org.hibernate.engine.spi.ExecutableList@48aca48b collectionCreations=org.hibernate.engine.spi.ExecutableList@13fd2ccd collectionRemovals=org.hibernate.engine.spi.ExecutableList@b9b00e0 collectionUpdates=org.hibernate.engine.spi.ExecutableList@506ae4d4 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@7d4f9aae unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])

Hibernate: update employees set e_name=?, e_age=?, e_salary=? where e_id=?

Session Info in Persistent State :
SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.varasofttech.pojo.Employee#9]],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@59505b48 updates=org.hibernate.engine.spi.ExecutableList@4efac082 deletions=org.hibernate.engine.spi.ExecutableList@6bd61f98 orphanRemovals=org.hibernate.engine.spi.ExecutableList@48aca48b collectionCreations=org.hibernate.engine.spi.ExecutableList@13fd2ccd collectionRemovals=org.hibernate.engine.spi.ExecutableList@b9b00e0 collectionUpdates=org.hibernate.engine.spi.ExecutableList@506ae4d4 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@7d4f9aae unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])

Session Info in Removed State :
SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.varasofttech.pojo.Employee#9]],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@59505b48 updates=org.hibernate.engine.spi.ExecutableList@4efac082 deletions=org.hibernate.engine.spi.ExecutableList@6bd61f98 orphanRemovals=org.hibernate.engine.spi.ExecutableList@48aca48b collectionCreations=org.hibernate.engine.spi.ExecutableList@13fd2ccd collectionRemovals=org.hibernate.engine.spi.ExecutableList@b9b00e0 collectionUpdates=org.hibernate.engine.spi.ExecutableList@506ae4d4 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@7d4f9aae unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])


1 comments: