Hibernate Lifecycle Of POJO Class Objects

  • Facebook
  • Google
  • LinkedIn
  • Twitter

The Hibernate framework is used to manage the persistence of objects. It allows objects to be associated with data present in the tables. When you can make a new object and save it into database or the data can be fetched from the database and given to user as database then hibernate objects go through certain stages in the life-cycle. The stages in the life cycle of an object managed by Hibernate are as follows.

  • Transient State
  • Persistent State
  • Detached State
  • Removed State

Transient State

When the object of a POJO class is created using the new operator then it will be in the Transient state, this object is not associated with any Hibernate Session. This object doesn`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.

Address address = new Address ("D-10 Okhla", 15, 110025); // Transient state

Persistent State

When the object is in persistent state, then it represent one row of the database, if the object is in persistent state then it is associated with the unique hibernate Session.

Hibernate supports the different ways to save an object to the database and load an object from the database

  • save()
  • saveOrUpdate()
  • persist()
  • get()
  • load()
  • list()
Address address = new Address ("D-10 Okhla", 15, 110025); // Transient state
session.save(address); // persistent state

Detached State

In order to convert or move an object from Persistence to Detached State, you need to clear the cache of the session or close the session by using following methods.

  • session.evict(); - evict method clear particular object from the cache
  • session.clear(); - clear method clears all objects from the cache
  • session.close(); - close method close the session
Address address = new Address ("D-10 Okhla", 15, 110025); // Transient state
session.save(address); // persistent state
session.close();  // detached state

Removed State

A persistent object is considered to be in the removed state when a delete() operation is called on it. remember that once you`ve deleted an object and moved to the removed state, you should no longer use that particular object for any reason.

Address address = new Address ("D-10 Okhla", 15, 110025); // Transient state
session.save(address); // persistent state
session.close();  // detached state
session.delete(address);  // removed state
      Advertisements