1. Introduction
In this tutorial, we’ll discuss life cycle of persistent objects in Hibernate.
In a Hibernate application, there can be two types of objects:
- An entity object which is mapped to the table and has properties mapped to the tables.
- Objects which are not directly recognized by the Hibernate.
Hibernate can work with both types of objects.
An object mapped to Hibernate can be in any of the following states:
- Transient
- Persistent
- Detached
- Removed
2. Transient objects
Hibernate does not manage transient objects or persist changes to transient objects in database. Transient objects exist in memory. Transient objects are independent of Hibernate. To persist changes to a transient object, you have to use session to save the transient object in the database. Hibernate then assigns an identifier to the object and then starts managing the object by changing the state of the object to persistent.
3. Persistent objects
Persistent objects exist in the database and managed by the Hibernate. If properties of a persistent object is changed, Hibernate will keep the database representation up to date when the application commits the changes. Persistent objects are associated with a session in Hibernate.
4. Detached objects
Detached objects are not associated with a session in Hibernate but have a database representation. Detached objects are not maintained by the Hibernate, i.e. changes in the properties of the object are not persisted in the database when application commits the changes. An object can be detached from the session if the session is closed or the object is evicted from the session by calling session’s evict()
method.
There could be need to make a persistent object as detached. For example, you may need to read the object from database, change it’s property and save it to somewhere else. In this case, you should detach the object from the session so that it is not managed by the Hibernate and any changes to the object are not persisted to the database.
In order to persist changes made to a detached object, the object much be reattached to a valid Hibernate session. A detached instance can be associated with a valid Hibernate session by calling one of the load()
, refresh()
, merge()
, update()
, or save()
methods on the session with a reference to the detached object.
5. Removed objects
A object is in removed state when a persistent instance is removed from the datastore. This is done by calling the delete()
method. When an object is in removed state, change done to the object is not reflected in the database.