Hibernate is picky about your Java objects. Hibernate prefers your objects to be in a certain “state”, and there are four different states that exist inside of the hibernate life cycle. They are-
Once you have a firm grasp of the different states that an object can be in Hibernate, you’ll be well on your way to mastering the Hibernate framework. Now let’s get this Hibernate life cycle lesson started.
When ever an object of a pojo class is Created(instantiated) using the new operator then it will be in the Transient state; this object is not associated with any Hibernate Session.
This object don’t have any association with any database table row. In other words any modification in data of transient state object doesn’t have any impact on the database table.
When the object is in persistent state, then it represent one row of the database, and it is associated with the unique 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.
You can create persistent objects via two ways:
- Loading the object from the database via Hibernate APIs
- Saving the object to the database via Hibernate APIs
Ways to Save an Object
Hibernate has a few different ways to save an object to the database, but the two main ways are as follows:
Invoking either of these Hibernate methods will shift your transient object into the persistent state (so long as the save is successful).
Ways to Load an Object
There are quite a few ways to load an object from a database. Here’s a couple that I use the most:
if we want to move an object from persistent to detached state, we need to close the session or clear the cache of the session.
- Here the reference to the object is still valid and the detached instance can 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 modification) persistent again.
This reattaching of object from detached to persistent state can be done by calling the following methods –
- lock() – It is reattached but not saved.
A persistent object is considered to be in the removed state when a delete() or remove() operation is called on it. Note that Once you’ve deleted an object and moved to the “removed” state, you should no longer use that particular object for any reason.