Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 39 ยท Caching and Performance

The Session Cache, Dirty Checking and Flushing

Understand Hibernate's first-level cache - the persistence context, identity guarantee, dirty checking snapshots, flush modes and when SQL really runs, with a runnable mini-session.

Every Hibernate Session has a built-in cache called the first-level cache or persistence context. You cannot turn it off, and it explains most of Hibernate's "magic": why find twice runs one query, why changing a setter updates the database without calling save, and why SQL appears later than you expect. Understanding it is the key to performance work, so this chapter starts here.

Hibernate is not available in the sandbox, so the real API is shown read-only. The runnable program builds a mini persistence context from a Map and snapshots, and you can watch the same behaviors happen.

What the persistence context does

The context is a map from (entity type, id) to the managed object, plus a snapshot of the values loaded from the database. Three guarantees come from it:

  1. Identity: within one session, find(Book.class, 1L) always returns the same Java object. a == b is true, and there is never a second copy with different state.
  2. Repeatable reads of entities: the second find is answered from the map without SQL.
  3. Automatic dirty checking: at flush time Hibernate compares every managed entity with its snapshot and issues update statements for the ones that changed.
Java
try (Session session = sessionFactory.openSession()) {
    Transaction tx = session.beginTransaction();

    Book a = session.find(Book.class, 1L);   // select ... where id = 1
    Book b = session.find(Book.class, 1L);   // no SQL: served from the context
    System.out.println(a == b);              // true

    a.setPrice(new BigDecimal("21.90"));     // no SQL yet
    tx.commit();                             // flush: update books set price=? where id=?
}

No save() or update() call is needed for a managed entity. This surprises newcomers, and it also causes accidental updates: a setter called in a "read-only" method is persisted if the entity is managed.

The entity states

State Meaning How you get there
Transient a plain object, unknown to Hibernate new Book()
Managed (persistent) in the context, tracked persist(book), find, query results
Detached has an id, but its session closed session closed or detach(), or clear()
Removed scheduled for deletion remove(book)

persist makes a transient object managed, merge copies a detached object's state onto a managed instance and returns that instance, and remove schedules a delete. Detached objects are not tracked: editing them does nothing until you merge them.

stateDiagram-v2
    [*] --> Transient: new Book()
    Transient --> Managed: persist()
    Managed --> Detached: close() / clear() / detach()
    Detached --> Managed: merge() returns a managed copy
    Managed --> Removed: remove()
    Removed --> [*]: flush deletes the row
    Managed --> Managed: find() / query result

The lifecycle of an entity inside a session.

When does SQL run? Flushing

Hibernate collects changes and writes them in a flush. A flush happens:

  • when the transaction commits,
  • before a query that might be affected by pending changes (in the default AUTO mode),
  • when you call session.flush().
Java
session.persist(new Book("Hibernate in Practice"));  // insert is delayed (with SEQUENCE ids)
List<Book> books = session.createSelectionQuery("from Book", Book.class).getResultList();
// AUTO flush: the insert is sent first, so the query sees the new book

Flush modes: AUTO (default), COMMIT (flush only at commit; queries may miss pending changes), ALWAYS (flush before every query) and MANUAL (only when you call flush(): handy for read-only work, because it also skips dirty checking).

Two details matter in practice:

  • IDENTITY ids force immediate inserts. A database-generated identity (GenerationType.IDENTITY) is only known after the insert, so persist executes the insert at once and Hibernate cannot batch inserts. Prefer SEQUENCE with a pooled optimizer when you insert many rows.
  • Flush order is fixed: inserts, then updates, then collection changes, then deletes (not your call order). Unique constraints can fail if you delete and re-insert the same key in one flush; call flush() between them.

Dirty checking has a cost

Every managed entity is compared to its snapshot at each flush. With 50,000 loaded entities, that comparison dominates the transaction. Ways to reduce it:

  • Use read-only queries or session.setDefaultReadOnly(true) for reports: no snapshots are kept.
  • Use DTO projections instead of entities when you do not edit.
  • Batch and clear: flush() then clear() every N rows in long jobs (batch processing).
  • Use @DynamicUpdate to update only the changed columns (a smaller update, not a faster dirty check).

A mini persistence context

This program is not Hibernate, but it models the same mechanics: an identity map, snapshots, dirty checking and a delayed flush. "Database" operations are counted and printed so you can see when they happen.

Java Identity map, snapshots and flush

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output shows one select for two find calls, no SQL at the moment of the setter call, and exactly one update at commit. Entity 2 was loaded but never changed, so it is not written.

Useful Session operations

Method Effect
flush() send pending changes now, without committing
clear() detach everything, empty the cache (changes not yet flushed are lost)
evict(entity) / detach(entity) remove one entity from the context
refresh(entity) reload the entity from the database, overwriting in-memory changes
contains(entity) is it managed in this session?
getReference(Book.class, id) a lazy proxy without a select
setReadOnly(entity, true) stop tracking one entity

getReference is perfect for setting associations without loading the target: order.setCustomer(session.getReference(Customer.class, 7L)) writes the foreign key with no select for the customer.

Common pitfalls

  • Long-lived sessions. A session kept open for a whole user session grows without bound and returns stale data. Scope it to one unit of work (one request or transaction).
  • Calling clear() before flush(). Pending changes are discarded silently.
  • Reading stale data. A second find never sees changes committed by another transaction: use refresh or a new session when freshness matters.
  • Comparing detached entities with ==. Different sessions load different objects. Implement equals/hashCode on a stable business key or on the id carefully.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the first-level cache guarantee within one session?

    The persistence context keeps one instance per (type, id), so repeated lookups return the same object and need no SQL.
  2. 2. Why do you not need to call save() after changing a managed entity?

    At flush, Hibernate compares each managed entity to the snapshot taken at load and writes the differences.
  3. 3. Which id strategy makes Hibernate execute the insert immediately on persist, preventing JDBC batching?

    With IDENTITY the id only exists after the insert, so Hibernate must run it at once.
  4. 4. What happens to pending, unflushed changes when you call session.clear()?

    clear() detaches everything without flushing. Call flush() first if you want the changes written.

Summary

  • The persistence context keeps one managed object per entity id, with a snapshot for dirty checking.
  • SQL is delayed until a flush: commit, a query in AUTO mode, or flush().
  • Entities are transient, managed, detached or removed; only managed ones are tracked.
  • Control the cost of dirty checking with projections, read-only mode and batch-and-clear.

Next: N+1 Queries and Fetch Strategies