The persistence context
See how the EntityManager tracks entities and moves them through their lifecycle.
Open this lesson in the learning hubKey points
- The persistence context is the EntityManager workspace: every entity it loaded or saved, held for the length of the transaction.
- Four states: transient (a plain new object), managed (tracked), detached (was tracked, context is gone), removed (queued for DELETE).
persistmakes an object managed.mergecopies a detached object back in and returns the managed copy - the original stays detached.- Inside one context, one row means one object. Load the same id twice and you get the same instance with no second SELECT.
- That identity map is the first-level cache. It is always on, one per EntityManager, and cannot be turned off.
Example
@Service
public class BookService {
@PersistenceContext
private EntityManager em;
@Transactional
public void lifecycle() {
Book book = new Book("Effective Java", LocalDate.of(2018, 1, 6)); // transient
em.persist(book); // managed, id assigned
Book again = em.find(Book.class, book.getId());
System.out.println(again == book); // true - no SELECT, same context
em.detach(book); // detached: edits are ignored
book.setTitle("Effective Java, 3rd ed");
Book managed = em.merge(book); // a managed COPY comes back
managed.setTitle("Effective Java"); // this one will be saved
em.remove(managed); // removed: DELETE at flush
}
}
Managed entities live in the persistence context. Everything Hibernate does starts there.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Hibernate course, and every lesson in it is listed on the Hibernate contents page.