Example & Tutorial understanding programming in easy ways.

What are the types of Hibernate instance states ?

When we talk about the Hibernate instance states, an instance of a persistent class can be in three different states. These states are defined in relation to  a persistence context. The Hibernate session object is the persistence context. The three different state are as below:


Transient: In hibernate an object is transient if it has just been initatiated using the new operator, and it is not associated with a Hibernate session. It has no persistent representation in the database and no identifier value has been assigned. Transient instance will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate session to make an object persistent ( and let hibernate take care of the sql statements that need to be executed for this transition ).


Persistent: When a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded . However, it is by definition in the scope of a session. Hibernate will detect any change made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual Update and synchronize the state with the database when the unit of work completes. Developers do not execute manual Update statements, or Delete statements when an object should be made transient.


Detached: In a detached instance is an object that has been persistent, but its session has been closed. This reference to the object is still valid, of course, and the detached instace might 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, a unit of work form the point of view of the user.

Read More →