Java.Hibernate.Beginner.When object becomes unattached ?

An entity becomes detached (unattached) when it was persistent in a session but is no longer associated with any open session. This happens in several common scenarios:


🔹 1) Session is closed

  • As soon as you call session.close(), all persistent entities managed by that session become detached.
    Example:
Session session = sessionFactory.openSession();
User user = session.get(User.class, 1L); // persistent
session.close();                         // user now detached

🔹 2) Transaction is rolled back

  • If you rollback a transaction, the session may leave entities in a detached state depending on configuration or manually evict them.

🔹 3) Evicting an entity manually

  • Calling session.evict(entity) removes the entity from the session’s first-level cache → the entity becomes detached immediately.
    Example:
session.evict(user); // user is now detached

🔹 4) Clearing the session

  • Calling session.clear() evicts all managed entities, turning them all into detached objects.

🔹 5) Serialization & deserialization

  • If you serialize an entity to send it across a network or store it temporarily, when you deserialize it later, it’s detached because it’s not connected to any session anymore.

🔹 How to recognize a detached object:
✅ It still has its identifier (e.g., primary key),
✅ It exists in memory,
❌ But it’s no longer tracked by any Hibernate session, so modifying it won’t automatically trigger database updates.

🔹 Example:

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

User user = session.get(User.class, 1L); // persistent
tx.commit();
session.close();                         // user now detached

user.setUsername("newName");             // change won't persist — user is detached

An object becomes detached when it was previously persistent but is no longer associated with an open session, like after closing the session or evicting the entity → changes to detached objects won’t be tracked or saved by Hibernate.

This entry was posted in Без рубрики. Bookmark the permalink.