hibernate

Hibernate Lifecycle States Tutorial

In hibernate; it is important for developers to understand whether an object is saved in the database or not. In this tutorial, we will explore the different lifecycle states of an object in the Hibernate framework.

1. Introduction

  • Object-Relational Mapping or ORM is the programming technique to map application domain model objects to the relational database tables
  • Hibernate is a Java-based ORM tool that provides the framework for mapping application domain objects to the relational database tables and vice versa. It provides the reference implementation of Java Persistence API that makes it a great choice as an ORM tool with benefits of loose coupling
  • A Framework that an option to map plain old Java objects to the traditional database tables with the use of JPA annotations as well as XML based configuration

Hibernate Lifecycle States - Hibernate overview
Fig. 1: Hibernate overview

1.1 Hibernate Annotations

  • Hibernate annotations are the newest way to define mappings without the use of a XML file
  • Developers use annotations to provide metadata configuration along with the Java code. Thus, making the code easy to understand
  • XML provides the ability to change the configuration without building the project. Thus, annotations are less powerful than the XML configuration and should only be used for table and column mappings
  • Annotations are preconfigured with sensible default values, which reduce the amount of coding required. For e.g., Class name defaults to Table name and Field names default to Column names

1.2 Download and Install Hibernate

You can read this tutorial in order to download and install Hibernate in the Eclipse IDE.

1.3 Download and Install MySQL

You can watch this video in order to download and install the MySQL database on your Windows operating system.

2. Lifecycle States of an Object in Hibernate

Hibernate is an object-relational mapping based java technology that saves, updates, delete a record in the database table. The object lifecycle in hibernate shows how the pojo objects are managed. Let us understand these states in detail with an example.

2.1 Transient State

A transient state is one where hibernate session is not associated with the object instance and does not represent a row in the database table. The pojo object is created using the new keyword and does not contain any primary key identifier.

Hibernate Lifecycle States - transient object in Hibernate
Fig. 2: A transient object in Hibernate

The following snippet represents a simple syntax to understand this state.

Code Snippet

// Employee object is a 'transient' state.
Employee emp = new Employee();
emp.setName("Andrew");

2.2 Persistent State

A persistent state is one where hibernate session is associated with the object instance and does represent a row in the database table with a valid primary key identifier.

Hibernate Lifecycle States - A persistent object in Hibernate
Fig. 3: A persistent object in Hibernate

Developers will have to use the methods like session.save(obj), session.update(obj), session.persist(obj) or session.saveOrUpdate(obj) to preserve the transient object to the database. The following snippet represents a simple syntax to understand this state.

Code Snippet

Session s = sessionFactory.openSession();

// Transient state.
Employee emp = new Employee();

// Persistent state. Hibernate will the employee object to the database.
s.saveOrUpdate(emp);

// Modification is automatically saved because the employee object is in persistent state.
emp.setName("Peter");

// Commit the transaction.
s.getTransaction().commit();

Always remember, the object in the persistent state will only be saved to the database when the transaction is committed.

2.3 Detached State

In this state, the persistent object still exists after the closure of the active session. In other words, the changes to the pojo object will not be reflected in the database and vice-versa.

Hibernate Lifecycle States - A detached object in Hibernate
Fig. 4: A detached object in Hibernate

Different methods like session.evict(obj), session.close() and session.clear() can be used to detach the persistent object. The following snippet represents a simple syntax to understand this state.

Code Snippet

// All the objects will be in the detached state after the execution of this line.
sessionObj.close();

2.4 Removed State

When the persistent object is deleted from the database, it is passed to the session’s delete(obj) method. At this state, java instance exists but any changes made to the object are not saved to the database. Developers can use the session.delete(obj) method to remove the database record and will no longer manage the pojo object. The following snippet represents a simple syntax to understand this state.

Code Snippet

// Removes a persistent instance from the datastore.
sessionObj.delete(obj);

3. Flowchart Diagram

Take a look at the below diagram to briefly understand these states.

Hibernate Lifecycle States - Hibernate object lifecycle
Fig. 5: Hibernate object lifecycle

4. Coding Example

Take a look at the below example to briefly understand these states.

ObjectLifecycle.java

package com.hibernate.util;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.hibernate.model.Employee;

public class ObjectLifecycle {

	public static void main(String[] args) {

		// 'emp' object is in 'TRANSIENT' state.
		Employee emp = new Employee();
		emp.setName("Patrick");
		emp.setDesignation("Sr. Manager");
		emp.setDepartment("Human Resource");

		// Creating the config instance & passing the hibernate config file.
		Configuration config = new Configuration();
		config.configure("hibernate.cfg.xml");

		// Session object to start the db transaction.
		Session s = config.buildSessionFactory().openSession();

		// Transaction object to begin the db transaction.
		Transaction t = s.beginTransaction();

		// Here 'emp' object is in 'PERSISTENT' state.
		s.save(emp);

		// 'emp' object will be saved to the database.
		t.commit();

		// Closing the session object. 'emp' object is in 'DETACHED' object.
		s.close();
	}
}

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

5. Conclusion

This post defines the different lifecycle state of a pojo object in the Hibernate framework.

  • Newly created pojo objects will be in the transient state
  • Persistent objects represent one row of the database table and are always associated with some unique hibernate session
  • Detached objects are those that have left the union with the session object
  • Removed objects are those that have been passed to the session’s delete(obj) method

Developers can download the sample code as an Eclipse project in the Downloads section.

6. Download the Eclipse Project

This was a beginners tutorial to illustrate the different lifecycle states of a pojo object in the Hibernate framework.

Download
You can download the full source code of this example here: HibernateObjectLifecycle

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
ak 47
ak 47
3 years ago

Very good! Best explanation on this topic I’ve seen so far

Back to top button