Table of contents
1.
Introduction  
2.
Hibernate Entities 
3.
Hibernate Lifecycle 
3.1.
State 1: Transient State 
3.2.
State 2: Persistent State
3.3.
State 3: Detached State
3.4.
State 4: Removed State 
4.
Frequently Asked Questions 
4.1.
What is a Persistent Entity?
4.2.
What is a Detached Entity?
4.3.
What is a Removed Entity?
5.
Conclusion 
Last Updated: Mar 27, 2024
Medium

Hibernate Lifecycle

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction  

Hibernate is a Java framework that simplifies the development of Java applications for interaction with the database. In Hibernate, a new object of an entity can be created and stored in the database, or the existing data of an entity can be fetched from the database. This entity is associated with the lifecycle and each object of the entity goes through several stages (mainly four) of the Hibernate lifecycle. 

So, in this article, we will discuss Hibernate Lifecycle in detail.

Hibernate Entities 

Before jumping directly into different stages of the Hibernate Lifecycle, let us look at some basic elements that are involved.  

Working with Hibernate involves Plain Java Objects (POJO). It will not be able to identify these POJO classes, in absence of hibernate-specific annotations, that is, in the raw form.

But when the POJOs are annotated properly with required annotations then hibernate will be able to identify and work with them. For instance, storing them in the database, updating them, etc. These POJOs are managed by hibernate entities or hibernate persistence context.  

A few built-in annotations of Java include @Override, @SuppressWarnings, and @Deprecated.

Hibernate Lifecycle 

Hibernate Lifecycle is basically the lifecycle of the mapped instances of the object/entity classes in hibernate. In Hibernate, either a new object of an entity can be created and stored it in the database, or the existing data of an entity from the database can be fetched. This entity is associated with the lifecycle and every object entity passes via the several stages of the lifecycle. 

There are four main states of the Hibernate Lifecycle :

  1. Transient State
     
  2. Persistent State
     
  3. Detached State
     
  4. Removed State 
     

Below is a pictorial representation of the Hibernate Lifecycle

Hibernate Lifecycle

Let us now look at all these stages in detail:

State 1: Transient State 

This state is the first state of an entity object. 

Whenever an object of a POJO class is instantiated using the new operator then the object is in the Transient State. The object is not associated with any hibernate session. Since it is not connected to any Hibernate Session, therefore this state is not connected to any database table. Therefore, in case any changes are made in the data of the POJO Class then the database table does not get altered. Transient objects are independent of Hibernate, and also they exist in the heap memory.

Changing new object to Transient State

There are two layouts in which a Transient state will occur. They are as follows:

  1. Whenever objects are generated by an application but are not connected to any session.
     
  2. The objects are generated by a closed session.

Below, a new object for the Player class is being created. Below is the code which involves the initialization of the Player object:

// The object arrives in the Transient state.
Player p = new Player(); 
p.setId(01);  
p.setFirst_Name("Rishi");   
P.setLast_Name("Sharma");
You can also try this code with Online Java Compiler
Run Code

State 2: Persistent State

Whenever the object is connected with the Hibernate Session, then the object moves into the Persistent State. 

There are two ways to convert to the Persistent State from the Transient State :

  1. Save the entity object in the database table, Using the hibernated session.
     
  2. Load the entity object in the database table, using the hibernated session.

 

In the Persistent state, every object represents one row in the database table. Therefore, if any changes in the data are made, then hibernate will see these changes and make those in the database table.

Converting Transient State to Persistent State

 Below are the methods given for the persistent state:

  • session.save(e);  
     
  • session.saveOrUpdate(e);
     
  • session.persist(e);
     
  • session.update(e);
     
  • session.merge(e);
     
  • session.lock(e);


Example,

// Transient State
Player p = new Player("Rishi Sharma", 01); 

// Persistent State
session.save(e); //Persistent State
You can also try this code with Online Java Compiler
Run Code

State 3: Detached State

The session has to be closed or its cache has to be cleared, to convert an object to the Detached State from the Persistent State. 

Since the cache is cleared or the session is closed, all changes made to the data do not affect the database table. Whenever required, the detached object can be reconnected to a new hibernate session. For reconnecting the detached object to a new hibernate session, the following methods are used:

  • refresh()
     
  • merge()
     
  • update()
     
  • load()
     
  • update()
     
  • save()
     

Below are the methods used for the Detached state :

  • session.evict(e);
     
  • session.detach(e);
     
  • session.clear();
     
  • session.close();
Converting Persistent State to Detached State

Example,

// Transient State
Player p = new Player("Rishi Sharma", 01); 

// Persistent State 
session.save(p); 

// Detached State
session.close(); 
You can also try this code with Online Java Compiler
Run Code

 

State 4: Removed State 

It is the last state in the Hibernate Lifecycle. In the removed state, Whenever the entity object is discarded from the database, then the entity object is said to be in the Removed state. It is achieved by calling the delete() operation. 

As the entity object is in the Removed state, whenever any change is done in the data, it will not affect the database table.

Note: To make a removed entity object, session.delete() is called.

Converting Persistent State to Removed State

Example,

// Transient State
Player p = new Player(); 
Session t = sessionfactory.openSession();
p.setId(01); 

// Persistent State
session.save(e);  

// Removed State      
session.delete(e);       
You can also try this code with Online Java Compiler
Run Code

Frequently Asked Questions 

What is a Persistent Entity?

A persistent entity represents one row of the database and is always related to some unique hibernate session. Changes to persistent objects are tracked by Hibernate and are saved into the database when commit calls occur. 

What is a Detached Entity?

A Detached Entity is one that was once Persistent in the past, and now it is no longer persistent. To persist changes done in detached objects, they must be re-attached to hibernate session. 

What is a Removed Entity?

A Removed Entity is a persistent object that has been passed to the session’s remove() method and soon will be deleted as soon as changes held in the session will be committed to the database. 

Conclusion 

This article extensively discusses the different stages of Hibernate Lifecycle. 

It goes on to explain each stage of Hibernate Lifecycle along with the diagrams and the functions involved.
To hold a tighter grip on the topic, we recommend you go through the blogs: Hibernate EnvironmentHibernate Configuration, and ORM.

We hope that this blog has helped you enhance your knowledge regarding Hibernate Lifecycle, and if you would like to learn more, check out our articles on Coding Ninjas Blogs
You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSQLSystem Design, and many more!

If you want to test your competency in coding, you may check out the Mock Test Series and participate in the Contests organized on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the ProblemsInterview Experiences, and Interview Bundle for placement preparations.

Nevertheless, you may consider our Courses to give your career an edge over others!

Do upvote our blog to help other ninjas grow. 

Happy Coding!

Live masterclass