Java.Hibernate.Medium.What happens when you modify a detached object?

Short Answer

When you modify a detached object, changes happen only in Java memory — Hibernate does not track or persist those modifications, because the object is no longer associated with any session.


🔎 Detailed Explanation

  • Once an object becomes detached (e.g., after session.close() or session.clear()), it keeps its data and identifier in Java memory, but Hibernate stops monitoring it.
  • Any changes you make will not be synchronized with the database automatically, because there’s no session tracking the object anymore.
  • If you call session.flush() or session.commit() later in a different session, Hibernate won’t include changes made to this detached object.
  • To persist modifications you made on a detached object, you must reattach it by:
    • session.update(detachedEntity) — reattaches if the entity exists in DB.
    • session.merge(detachedEntity) — copies changes to a managed instance.

🧑‍💻 Code Example

Session session1 = sessionFactory.openSession();
Transaction tx1 = session1.beginTransaction();

MyEntity entity = session1.get(MyEntity.class, 1L); // Persistent
tx1.commit();
session1.close(); // Entity becomes Detached

entity.setName("Changed in Detached State"); // Hibernate doesn't track this

Session session2 = sessionFactory.openSession();
Transaction tx2 = session2.beginTransaction();

// Reattach to persist changes:
session2.update(entity); // OR session2.merge(entity)

tx2.commit();
session2.close();

🔥 What if you DON’T reattach?

✅ The modified detached object’s changes will remain only in Java memory.
✅ Hibernate will not generate any SQL for these modifications.
✅ The database remains unchanged, leading to data inconsistency if you expected your changes to persist.


📌 Key Takeaways

✅ Detached objects are not tracked, so modifications won’t be saved.
✅ Reattach with update() or merge() to persist changes.
✅ Forgetting to reattach detached entities is a common source of bugs, especially in web apps where objects often cross session boundaries.

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

Leave a Reply

Your email address will not be published.