In this tutorial we will discuss what are the states of objects in Hibernate framework. We know Hibernate is an ORM (Object Relational Mapping), which is an automated persistent of objects in a Java application to the tables in a relational database.

Hibernate defines and supports three different object states: transient, persistent and detached.

Transient State

A new instance, of a class which, is not associated with a Session, has no representation in the database and no identifier value, is considered transient by Hibernate. So it has just been instantiated using the new operator.

Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore.

Consider the following example for transient state,

User user = new User(); // user is in a transient state
user.setUserName("Sushil");

Persistent State

A persistent instance has a representation in the database and an identifier value, which is associated with a Session. We can make a transient instance persistent by associating it with a Session.

It might just have been saved or loaded, however, it is by definition in the scope of a Session. 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.

Long id = (Long) session.save(user); // user is now in a persistent state

Detached State

Now, if we close the Hibernate Session, the persistent instance will become a detached instance, so it isn’t attached to a Session anymore (but can still be modified and reattached to a new Session later though).

Therefore, a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state.

A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e., a unit of work from the point of view of the user.

session.close(); //user in detached state

That’s all about transient, persistent and detached states of object in Hibernate.

Thanks for reading.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *