Monday, July 28, 2014

Hibernate Entities Life cycle

The entities managed by Hibernate has a life-cycle associated with them. Either you can make a new object in heap and save it into database or the data can be fetched from the database and given to user as database. The hibernate objects go through certain stages in the life-cycle. Only entity objects participate in the life cycle. The value objects do not participate in the life-cycle. The stages in the life cycle of an entity managed by Hibernate are as follows:
Transient Objects
When objects are created in the Java layer with new or similar operator and they have no corresponding record existing in database than these objects are termed as Transient objects. These
objects exist in heap. The primary key attribute of this object is still not set. Transient objects are non transactional and in fact Hibernate has no knowledge of these objects at this point of time, Objects that are referenced only by other transient instances are, by default also transient. For an instance to transition from transient to persistent state or to go managed state, it requires either a call to persistence manger or the creation of a reference from an already persistent instance.
Persistent Objects
Persistent entity is again an object in heap but it has a valid database identity associate with it.
The entity goes into persistent object by one of following means:

  • Objects instantiated by application and then made persistent by calling one of the methods on the persistent manager.
  • The objects become persistent when a reference is created from one of the persistent object.
  • The entities retrieved from the database either by doing query, lookup or navigating the object graph.
Persistent instances are always associated with a persistent context and Hibernate knows about them and may track them for dirty checking.
Removed Object
An object scheduled for deletion either by calling delete or because of orphan deletion of entities. One should not use the object in Java layer as the database record will be deleted at the end of session. A logic build around these objects might get into trouble.
Detached Object
The object in persistent state go into detached state after the persistent context is closed. Detached objects can be brought into other persistent context by reattachment or merging. Detached object still has a valid primary key attribute but it is no longer managed by Hibernate.

1 comment:

  1. The concept is explained in clear and simple way. Thanks friend!!

    ReplyDelete