Objects in Hibernate go through any of the three states: transient, persistent and detached.
When an object is just instantiated, it is said to be in transient state. A transient object does not yet correspond to any row in the database table. Consequently, any modification on a transient object has no effect on the underlying table. Consider the following example:
Book aBook = new Book(”Hibernate”, 450);
Here, aBook is a transient object. Hibernate is not aware of aBook so far.
When an object is associated with a hibernate session in some way, it is said to be in persistent state. The following are some ways to associate an object with a session:
- Load an already existing object from database
- Store/Update an object to database
The Session interface provides a number of persistence methods to associate an object with the session such as save() , update() , saveOrUpdate() , merge() , load() , get() , persist() , etc.
A persistent object corresponds to a row of the database table. Persistent objects are stored in the session’s cache. When a session is flushed (using commit() or rollback()), all persistent objects in session’s cache are saved to the database. So, it is not mandatory to explicitly save or update persistent objects, upon modification, to the database, if they are part of an active transaction. They are saved when the transaction is committed.
A detached object is one which was in a session’s cache earlier, but no longer remains there. This may happen if
- cache is completely cleared (using clear() method), or
- object is removed from cache (using evict() method) or
- session is closed (using ciose() method),
- transaction is committed.
Unlike a transient object, a detached object did correspond to a table row. However, it does not currently correspond to any table row. A detached object, however, may be attached to a session later which makes it persistent again.
Source: Uttam Kumar Roy (2015), Advanced Java programming, Oxford University Press.