Menu

Entity Lifecycle and Persistence Context

Entity Lifecycle and Persistence Context

Entity States

Every entity object is in one of four states, and Hibernate behaves differently in each.

State

Meaning

TransientCreated with new, not linked to any session, no database row
PersistentManaged by an open session and tracked for changes
DetachedWas persistent, but its session was closed or the object was detached
RemovedMarked for deletion, and the row is deleted at flush

The Persistence Context

The persistence context is the set of entities a session is currently managing. It is also called the first-level cache.

Within one session, loading the same row twice returns the same object, and the second load does not hit the database. Hibernate also keeps a snapshot of each managed entity.

At flush time, it compares the entity with the snapshot, and any difference produces an update. This is called dirty checking.

Student s = new Student("Asha");
session.persist(s);
s.setName("Asha K");
session.flush();

session.detach(s);
Student managed = session.merge(s);
session.remove(managed);

Code Explanation:

  • After new, the object is transient. persist() makes it persistent.
  • setName() needs no save call, because dirty checking sends the update on flush.
  • flush() writes pending changes to the database. It also runs automatically before a commit.
  • detach() removes the object from the session, so later changes are no longer tracked.
  • merge() copies the state of a detached object onto a managed instance and returns that instance. The original stays detached.
  • remove() schedules deletion of a managed entity.

Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details