How does Hibernate Distinguish Between Transient (i.e. newly instantiated) and Detached Objects

Hibernate uses the “version” property, if there is one.

If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys.

Hibernate uses the concept of entity state to distinguish between transient (newly instantiated) and detached objects. Entity state refers to the current state of an object in the context of its association with the Hibernate Session.

  1. Transient State:
    • Objects are in the transient state if they have just been instantiated using the new keyword, and they are not associated with any Hibernate Session.
    • These objects are not yet saved in the database and are not managed by Hibernate.
  2. Detached State:
    • Objects are in the detached state if they were previously associated with a Hibernate Session but have been disconnected from that session.
    • This can happen when the session is closed, or the object is explicitly detached using methods like evict() or clear().
    • Detached objects were once persistent (saved in the database), but they are no longer actively managed by Hibernate.

To distinguish between these states, Hibernate relies on the concept of the session. When an object is associated with a Hibernate Session, it becomes part of the persistence context. Hibernate keeps track of changes to objects within this context and manages their synchronization with the database.

When an object is in the transient state, it has not yet been associated with a session, and Hibernate is not aware of its existence. When an object is detached, it means it was part of a session but has been removed or disconnected from that session.

In summary, Hibernate distinguishes between transient and detached objects based on their association with a Hibernate Session. Transient objects have never been associated, while detached objects were once associated but have been disconnected.