Hibernate Object States – Transient, Persistent and Detached

Hibernate Object States

In this tutorial I will discuss what are the states of objects (transient persistent detached objects) in Hibernate framework. You might be knowing that 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 (persistence storage) 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, the instance from User class has just been created and not associated with any database session:

User user = new User(); // user is in a transient state

Persistent State

A persistent instance has a representation in the database and an identifier value, which is associated with a Session. You 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 you 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. You may 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 an object in Hibernate ORM framework.

Leave a Reply

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