Object Lifecycle and states in Hibernate

Looking at the state of an object in Hibernate, we will get to know whether object is saved into Database or not.

The 3 states of an object in Hibernate

Transient

Persistent

Detached


Hibernate_ObjectState_01

Let’s see these states in detail with example

Transient state

A transient object is one that Hibernate has no idea on it.

It’s the first state of any object in the Hibernate Life cycle.

Any object which is not associated with hibernate session and does not represent a row in the database is considered as transient.

It will be garbage collected by JVM,If no other object is referencing it.

An object that is created using the new() operator is in transient state.

When the object is in transient state then it will not contain any identifier (primary key value).

We have to use session methods like save, persist or saveOrUpdate methods to persist the transient object.

Example:

  1. User user = new User();
  2. user.setName("kb");
User user = new User();
user.setName("kb");


Now user object is not associated with any session and hence it can be called as Transient object.

Persistent state

An object that is associated with the hibernate session is called as Persistent object.

When an object is in a persistent state, Hibernate is totally aware of it.

It also represents one row of the database and consists of an identifier value.

We can make a transient instance persistent by associating it with a Session like below

  1. Long id = (Long)session.save(user);
  2. //This object is in persistent state
Long id = (Long)session.save(user); 
//This object is in persistent state


Object can get the Persistent state in the below 2 scenarios


1) Load the object from the Database using Hibernate API
In this case, we load the existing object from the database and it will be automatically associated with the session.

2) Save the object into the database using Hibernate API
In this case new transient object created using “new” operator will be attached to the session and it becomes Persistent object.

Note: Object in Persistent state will be saved only when the Transaction is committed.

Detached state

The detached state is given to an object that was previously “attached” to the Session (persistent state) but has now left the association with the Session.

Example:

  1. Session.close();
  2. //All the objects will be in detached state after this line execution
Session.close();
//All the objects will be in detached state after this line execution

All the persistent objects within the Session will get the detached state when we close the session.

If we would have done transaction commit before closing the Session then all Persistent objects will be saved into Database otherwise those persistent objects will be lost.

So object in Detached State may present in the Database but not guaranteed.

So most important thing is to commit the transaction before closing the Session.

Look at the below diagram for better understanding on these states

Hibernate_ObjectState_02

Example to represent all the states together

  1. public class HibernateObjectStates {
  2. public static void main(String[] args)
  3.  {
  4.   User user= new User();
  5.                 user.setName("John");
  6.                 user.setCity("Newyork");
  7.   //’user’  is in  TRANSIENT state
  8.  
  9.                 SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
  10.                 Session session = sessionFactory.openSession();
  11.                 session.beginTransaction();
  12.  
  13.                 session.save(user);
  14.   //Here ‘user’ is in PERSISTENT state
  15.    
  16.                 session.getTransaction().commit();
  17.   //’user’ will be saved to Database
  18.  
  19.                 session.close();
  20.   //’user’  is in  DETACHED object
  21.  }
  22. }
public class HibernateObjectStates {
public static void main(String[] args) 
 {
  User user= new User();
                user.setName("John");
                user.setCity("Newyork");
  //’user’  is in  TRANSIENT state
  
                SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
                Session session = sessionFactory.openSession();
                session.beginTransaction();
  
                session.save(user);
  //Here ‘user’ is in PERSISTENT state
   
                session.getTransaction().commit();
  //’user’ will be saved to Database

                session.close();
  //’user’  is in  DETACHED object
 }
}


Transient VS Detached state

Few people get confused with Transient and Detached State as both of them are not associated with the Session.

I believe below explanation will clear that confusion

Transient objects do not have any association with either database or session objects.
They are just created using “new”.

Once the reference is lost, object is collected by garbage collector.

The commits and rollbacks operation will have no effects on these objects.

They can become persistent objects through the save() method of Session object.

Hibernate does not even know that there is an object if it’s in Transient state

Detached objects will have corresponding entries in the database but they are not associated with the Session.

Detached objects were associated with Session and known to hibernate in the past but not currently.

The detached object can be reattached to session to make it persistent again.

Note:
If object is in transient state, then it is guaranteed that it has no existence in the database.
If object is in detached state, even though it is not guaranteed (depends on transaction is committed or not) but there is a possibility that object may have existence in the database already.

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on