Skip to content
javahacks.dev
Hibernate

Hibernate First Level Cache and Flush Modes Explained

How the Hibernate first level cache and flush modes work: identity map behaviour, AUTO flush before queries, COMMIT and MANUAL modes and batch clearing.

6 min read
Summarize in AI
Flat illustration of an entity class mapped to a database table, with the Hibernate, OpenJDK, PostgreSQL and MariaDB logos.

Two Hibernate concepts explain a large share of surprising SQL and surprising data: the cache that every session has, and the moment changes are written. Neither is optional, and both can be tuned. This uses Hibernate 7 on JDK 25. The states of entities in that context are in entity states.

The first level cache

The persistence context keeps a map from entity type and id to the managed object.

java
@Transactional
void demo() {
    Customer a = em.find(Customer.class, 1L);   // SELECT ... where id = 1
    Customer b = em.find(Customer.class, 1L);   // no SQL
    System.out.println(a == b);                  // true
}

Within the session, an entity row has one Java object. This guarantees consistent identity and makes repeated lookups free. It is not the second level cache (a cross session, optional cache) and not shared among requests, because each transaction has its own context. Closing it discards everything.

Queries behave differently:

java
List<Customer> all = em.createQuery("from Customer", Customer.class).getResultList();  // always SQL

A JPQL query always runs against the database. For each row returned, if the context already holds that id, Hibernate returns the existing object and ignores the fresh column values. A query result can therefore be stale relative to the row, for entities you have already loaded and changed in memory. Use em.refresh(entity) to reload one.

Flush: when changes become SQL

Changes to managed entities sit in memory until a flush. The flush runs the INSERT, UPDATE and DELETE statements, in an order Hibernate chooses to respect foreign keys. It does not commit; the transaction does.

Flush modeBehaviour
AUTO (default)Flush before a query that could be affected, and at commit
COMMITFlush only at commit, queries may not see pending changes
ALWAYSHibernate extension: flush before every query
MANUALNever automatically, only when flush() is called

AUTO exists to keep queries consistent with your changes:

java
@Transactional
void promote(long id) {
    Customer c = em.find(Customer.class, id);
    c.setTier("GOLD");                                    // pending
    long golds = em.createQuery("select count(c) from Customer c where c.tier = 'GOLD'", Long.class)
                   .getSingleResult();                    // AUTO flushes UPDATE first
}

Without the flush, the count would not include the change. Hibernate flushes only when the pending changes touch the tables the query reads, which is why unrelated queries do not cause writes. Native SQL queries are different: Hibernate cannot tell which tables they use, so it flushes for them unless you specify the query spaces.

Set a mode on a query or session:

java
em.setFlushMode(FlushModeType.COMMIT);
query.setHint("org.hibernate.flushMode", "MANUAL");

MANUAL suits read-only operations, where it avoids dirty checking cost, see also @Transactional(readOnly = true) which Spring maps to it.

Cost of a large context

Every managed entity is tracked, and each flush compares them all with their snapshots. A batch that loads 100,000 entities makes each flush slower and uses memory. The pattern for batch work:

java
for (int i = 0; i < items.size(); i++) {
    em.persist(items.get(i));
    if (i % 50 == 49) {
        em.flush();
        em.clear();          // detach everything, free memory
    }
}

Flush to write, then clear to release. The batch size should match hibernate.jdbc.batch_size, see sequence generators and batching. The comparison process is in dirty checking.

Seeing it

Log SQL with hibernate.show_sql or the org.hibernate.SQL logger and add a log line before and after a query. An UPDATE appearing before a SELECT is an AUTO flush. See debugging Hibernate SQL.

One identity per row in a session

The first level cache guarantees that within one session a row maps to one object. Loading the same id twice returns the same instance, and the second call runs no SQL:

java
Order a = em.find(Order.class, 42L);
Order b = em.find(Order.class, 42L);
System.out.println(a == b);       // true, one select

A JPQL or criteria query behaves differently. It always runs the SQL, and for each row returned it checks the context: a row whose id is already managed gives back the existing instance, and the fresh column values are ignored. If another transaction changed the row in the meantime, the query result still carries the old values, because the managed instance wins. Call em.refresh(order) to reload one entity, or em.clear() to drop everything and read again.

A flush mode decision table

The default AUTO flushes before a query when pending changes touch tables that the query reads, so queries see the session's own writes. COMMIT waits until the transaction ends. The mode is set per session or per query:

java
em.setFlushMode(FlushModeType.COMMIT);

List<Order> open = em.createQuery("select o from Order o where o.status = 'OPEN'", Order.class)
        .setFlushMode(FlushModeType.COMMIT)
        .getResultList();
SituationModeWhy
Normal service codeAUTOQueries see what the same transaction wrote
A read-only reportCOMMIT, or a read-only transactionNo dirty checking and no flush before each query
Many queries after a few changesCOMMIT on the queriesAvoids a flush per query
A native SQL query after entity changesFlush explicitlyHibernate cannot tell which tables a native query reads, and an explicit call is needed

The last row is a classic. A native query run after save() returns stale data, because AUTO does not know the native SQL reads that table, unless the query declares the synchronized entity classes. Call em.flush() first.

Batch work needs the cache emptied

Every entity read or persisted in a session stays in the cache until the session ends. A loop over 100,000 rows grows the heap and slows every flush, because dirty checking compares each managed entity with its snapshot. Flush and clear at a fixed batch size, and set the JDBC batch size to match:

properties
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=true
java
for (int i = 0; i < rows.size(); i++) {
    em.persist(rows.get(i));
    if (i % 50 == 49) {
        em.flush();
        em.clear();
    }
}

After clear(), earlier entities are detached, so do not use them afterwards. Identity generation with GenerationType.IDENTITY disables JDBC batching of inserts, since each insert must run to obtain the key. A sequence with an allocation size of 50 keeps batching available.

What the dirty check costs

At flush, Hibernate compares every managed entity's current state with the snapshot it took on load. With 10,000 managed entities and 20 fields each, that is 200,000 comparisons for each flush, even when nothing changed. A read-only method that loads a large graph pays it for nothing. Mark such a transaction readOnly = true and Hibernate skips the snapshot and the check, saving both time and memory. A query that returns DTO projections avoids the problem completely, since nothing is managed.

Reading the session's state

em.contains(entity) says whether an object is managed, and Hibernate.isInitialized(proxy) says whether a lazy proxy has loaded. In a test, SessionImplementor.getPersistenceContext().getNumberOfManagedEntities() shows the cache size, which is how to confirm that a batch loop is clearing as intended.

Teaching the model to the team

The persistence context explains most Hibernate surprises, and a short internal session pays back quickly. Draw the picture: an entity manager holds a map of loaded entities, a list of pending changes and a connection that is used at flush. Walk through three examples, the repeated find, the query after a change and the batch loop, and let people predict the SQL before running it with logging on.

Teams that understand the picture stop adding saveAndFlush calls to make symptoms go away, and they read the SQL log with confidence.

Where this does not apply

Stateless sessions have no cache. A second level cache is a separate feature with its own risks. Documentation: the Hibernate persistence context chapter and the FlushModeType Javadoc.

Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.