What are detached, persistent and transient objects in hibernate? Please explain with an example.
A detached entity is just an ordinary entity POJO whose identity value corresponds to a database row. The difference from a managed entity is that it's not tracked anymore by any persistence context. An entity can become detached when the Session used to load it was closed, or when we call Session.
Persistent objects are instances of POJO classes that you create that represent rows in the table in the database. According to hibernate-doc an instance of POJO class representing table in database goes through 3 states of which persistent is one of them.
Persistent refers to an object's ability to transcend time or space. A persistent object stores/saves its state in a permanent storage system with out losing the information represented by the object. A non-persistent object is said to be transient or ephemeral. By default objects are considered as non-persistent.
In the context of Hibernate's Session, objects can be in one of three possible states: transient, persistent, or detached.
A new
instance of a persistent class which is not associated with a Session
, has no representation in the database and no identifier value is considered transient by Hibernate:
Person person = new Person(); person.setName("Foobar"); // person is in a transient state
A persistent instance has a representation in the database, an identifier value and is associated with a Session
. You can make a transient instance persistent by associating it with a Session
:
Long id = (Long) session.save(person); // person is now in a persistent state
Now, if we close
the Hibernate Session
, the persistent instance will become a detached instance: it isn't attached to a Session
anymore (but can still be modified and reattached to a new Session
later though).
All this is clearly explained in the whole Chapter 10. Working with objects of the Hibernate documentation that I'm only paraphrasing above. Definitely, a must-read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With