✅ Short Answer
- Transient: object exists in Java memory only, not yet saved to the database or associated with a session.
- Persistent: object is associated with an open Hibernate session, and changes are automatically tracked and saved.
- Detached: object was persistent, but the session was closed or cleared, so it’s no longer tracked by Hibernate.
🔎 Detailed Explanation
🔹 Transient State
- Object is created with
new
, but:- Has no identifier assigned by Hibernate.
- Not associated with any session.
- No corresponding row in the database yet.
- Changes to the object are not tracked by Hibernate.
- Example:
MyEntity entity = new MyEntity(); // Transient
entity.setName("New");
🔹 Persistent State
- Object is associated with an open Hibernate session:
- Loaded via
session.get()
/session.load()
. - Or saved via
session.save()
,session.persist()
.
- Loaded via
- Hibernate tracks changes automatically and will propagate them to the database when the session is flushed or transaction committed.
- Example:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
MyEntity entity = session.get(MyEntity.class, 1L); // Persistent
entity.setName("Updated"); // Hibernate tracks this change
tx.commit();
session.close();
🔹 Detached State
- Object was previously persistent, but now:
- The session was closed or
session.clear()
was called. - The object still has its identifier (primary key), but Hibernate no longer tracks changes.
- Changes made to detached objects are not saved automatically.
- The session was closed or
- To persist changes, you must reattach the object using
session.update()
,session.merge()
, or similar methods. - Example:
Session oldSession = sessionFactory.openSession();
MyEntity entity = oldSession.get(MyEntity.class, 1L); // Persistent
oldSession.close(); // entity becomes Detached
entity.setName("Detached Change"); // Change is not tracked!
🧑💻 Code Walkthrough
// Transient
MyEntity entity = new MyEntity();
entity.setName("Transient");
// Persistent
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(entity); // Now persistent
entity.setName("Persistent Change"); // Hibernate tracks it
tx.commit();
session.close(); // Entity becomes detached here
// Detached
entity.setName("Detached Change"); // Hibernate doesn't track this anymore
📊 Quick Comparison Table
State | Associated with Session? | In Database? | Changes auto-tracked? |
---|---|---|---|
Transient | ❌ No | ❌ No | ❌ No |
Persistent | ✅ Yes | ✅ Yes/Will be | ✅ Yes |
Detached | ❌ No (was associated) | ✅ Yes | ❌ No |
📌 Key Takeaways
✅ Transient: brand new objects — no session, no DB row.
✅ Persistent: session-managed objects — changes auto-saved.
✅ Detached: previously persistent, but session is gone — changes ignored unless reattached.
✅ Understanding these states helps you avoid subtle bugs, like missing updates or unexpected inserts.