🔹 1️⃣ Transient objects
✅ Newly created objects that are not associated with any Hibernate session and have no representation in the database yet.
✅ Hibernate does not track them → changes are ignored unless you explicitly save them.
✅ Created with new
but not yet saved or loaded.
Example:
User user = new User(); // transient
user.setUsername("alice");
🔹 2️⃣ Persistent objects
✅ Objects that are associated with an open Hibernate session → Hibernate tracks their state and automatically synchronizes any changes with the database at flush or commit.
✅ They can become persistent by:
- Saving a transient object:
session.save(user)
- Loading from DB:
session.get(User.class, 1L)
- Reattaching a detached object:
session.update(user)
orsession.merge(user)
Example:
Session session = sessionFactory.openSession();
session.beginTransaction();
User user = session.get(User.class, 1L); // persistent
user.setUsername("bob"); // tracked → auto-updated on commit
session.getTransaction().commit();
session.close();
🔹 3️⃣ Detached objects
✅ Objects that were persistent but the session is now closed or the entity was evicted → they still exist in memory but are no longer tracked by Hibernate.
✅ Changes to detached objects will not be persisted until you reattach them.
Example:
Session session = sessionFactory.openSession();
User user = session.get(User.class, 1L); // persistent
session.close(); // user becomes detached
user.setUsername("carol"); // changes not tracked
// Reattach if needed:
Session session2 = sessionFactory.openSession();
session2.beginTransaction();
session2.update(user); // now persistent again
session2.getTransaction().commit();
session2.close();
🔹 Summary table:
State | Associated with Session? | Tracked? | Example |
---|---|---|---|
Transient | ❌ No | ❌ No | new User() |
Persistent | ✅ Yes | ✅ Yes | session.get() or save() |
Detached | ❌ No (was persistent) | ❌ No | After session.close() |