Java.Hibernate.Beginner.Explain Enity lifecycle

Hibernate defines three states an entity can be in during its lifetime:

🔹 1) Transient

  • What it means: The object exists in Java memory but is not yet known to Hibernate, and not saved to the database.
  • Example:
User user = new User();         // new object in memory
user.setUsername("john");       // but not saved anywhere

If you don’t save it, it’s just a regular Java object with no connection to the DB.

🔹 2) Persistent

  • What it means: The object is associated with an open Hibernate session, and any changes to it are automatically tracked and synchronized with the database (e.g., on flush() or commit()).
  • Example:
Session session = sessionFactory.openSession();
session.beginTransaction();

User user = new User();
user.setUsername("john");
session.save(user);            // user is now persistent!

user.setEmail("john@example.com"); // Hibernate will notice this change
session.getTransaction().commit();
session.close();

While the session is open, any modifications are automatically saved to the database.

🔹 3) Detached

  • What it means: The object was persistent, but now the session is closed, or you manually evicted it — so Hibernate is no longer tracking it.
  • Example:
Session session = sessionFactory.openSession();
User user = session.get(User.class, 1L); // persistent
session.close();                         // session closed

user.setUsername("newName");  // user is now detached
// Hibernate won’t save this change automatically, because the session is gone.

To update changes in a detached object, you must reattach it with session.update() or session.merge().

🔹 Quick analogy:

  • Transient: A draft email you haven’t sent or saved yet.
  • Persistent: An email draft you’re editing in your email app — changes are saved live.
  • Detached: A saved draft you’ve closed; you can reopen it later, but changes won’t sync unless you explicitly save again.

Key takeaway:

  • Transient → Not yet saved or tracked.
  • Persistent → Tracked by Hibernate in an open session.
  • Detached → Previously tracked, but the session ended — so changes are no longer auto-saved.
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.