Video in progress

What is the persistence context?

The persistence context is the set of managed entities inside one EntityManager (a Session in Hibernate). It keeps one object per id, tracks changes, and turns them into SQL on flush.

📖 Answer

You can picture it as an "id → object" map. In Spring, one transaction usually means one persistence context.

Three things follow from that:

@Transactional
public void check(Long id) {
    User a = em.find(User.class, id); // a SELECT is sent
    User b = em.find(User.class, id); // no SELECT, served from the context
    System.out.println(a == b);       // true
}
  1. Within one transaction, an entity with a given id is always a single Java object.
  2. Changes to a managed object are written to the database automatically (dirty checking).
  3. SQL isn't sent right away but on flush: Hibernate collects the writes.

There is a risk too: until the context is cleared, every loaded object stays in memory. If you read 500 thousand rows with find or a query in one transaction, the heap can fill up. For large batch jobs you call flush() and clear() periodically.