Java.Hibernate.Beginner.What are transient, persistent, and detached objects in Hibernate?

🔹 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) or session.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:

StateAssociated with Session?Tracked?Example
Transient❌ No❌ Nonew User()
Persistent✅ Yes✅ Yessession.get() or save()
Detached❌ No (was persistent)❌ NoAfter session.close()
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.