Sunday, May 8, 2011

Different states of an Object in hibernate

In hibernate, object can be in any of these states:

  • Transient object or in-memory objects
  • Persistent Object
  • Detached object

When the object is created, its transient in nature. They have not yet connected to database, so they are like in-memory objects.

When an object is associated with the persistence layer, its a persistent object.

When an object is no more associated with the persistent layer, its a detached object.

How do Hibernate knows about these object states?

All objects are similar to each other in JVM. So JVM provides no method of differentiating these objects. But its hibernate which is able to differentiate these objects.

Transient objects are like normal in-memory objects, which have some data into them, which is persisted after they are changed to persistent object.

Persistent objects are the objects which are associated with persistent context. Being associated with persistent context means, modification in state of persistent object is synchronize with the underlying database.

In case of detached object, the persistent context has been closed on behalf of some transactional process being commited / roll back. Modifying the state of this object will not reflect any changes in database, until and unless this object is reattached to the persistence context.

So Transient and Detached object, both are not attached to persistence context, but, 

how do Hibernate differentiates between transient and detached object ?

Again JVM can't differentiate between the 2, but hibernate can. In case of transient object, primary key of the object is not initialized while in case of detached object this is not the case. It is already being initialized, because its been in touch with persistence context earlier.

No comments:

Post a Comment

Chitika