Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What is dirty checking in Hibernate, and when does a flush happen by default?

Dirty checking is how Hibernate finds changes by itself: at flush time it compares each managed entity's current values with the snapshot it took when the entity was loaded, and writes an UPDATE for every entity that differs, so we never call save() for managed entities. With the default FlushModeType.AUTO, a flush happens before the transaction commits and before a query whose results could be affected by pending changes. We can also call flush() ourselves, which sends the SQL but does not commit, and FlushModeType.COMMIT limits flushing to commit time.

Why this question is asked

Dirty checking explains several things that surprise developers: updates that appear without a save() call, queries that suddenly trigger UPDATE statements, and services that spend a lot of CPU in Hibernate even though they mostly read. Interviewers ask about it because it separates people who use JPA like a remote API from people who understand its unit of work. In this answer, we will recap managed entities and snapshots, follow dirty checking step by step, see exactly when an automatic flush happens, and look at explicit flush() and the COMMIT flush mode.

1A Quick Recap of Managed Entities and Snapshots

An entity is managed when the persistence context tracks it: we loaded it with find() or a query, or we persisted it in this transaction. For each managed entity loaded from the database, Hibernate keeps a snapshot, a copy of the column values exactly as they were read. The snapshot is the reference point for later comparison.

A flush is the moment Hibernate sends pending changes to the database as SQL statements: inserts for persisted entities, updates for changed ones and deletes for removed ones. Flushing is not committing. The statements run inside the open transaction, and a rollback can still undo them.

2How Dirty Checking Works, Step by Step

When a flush starts, Hibernate walks over every managed entity in the persistence context. For each one, it reads the current value of every mapped attribute and compares it with the snapshot, attribute by attribute, using the equality rules of each attribute's type. If nothing differs, the entity is clean and nothing is written. If something differs, Hibernate schedules an UPDATE, then refreshes the snapshot so the next flush compares against the new values.

Java
@Transactional
public void raisePrice(long id) {
Product p = em.find(Product.class, id); // select; snapshot: price=10.00, name=Pen
p.setPrice(new BigDecimal("12.00")); // only the Java field changes
} // flush before commit: price differs from snapshot
// update product set name=?, price=? where id=? (all columns by default)
// commit
Step throughWhat a flush does with each managed entity
  1. Flush startsbefore commit, before an affected query, or on flush()
  2. Take the next managed entity
  3. Current values equal the snapshot?
    Yesnothing to writeNoschedule an UPDATE
  4. Update the snapshotnext flush compares with the new values
  5. More managed entities?
    Yestake the next oneNosend inserts, updates, deletes in order

5 steps in order. Play them, or step through them one at a time.

The work grows with the number of managed entities, not with the number of changes.

Notice that there is no save() call. Calling repository.save(p) here would add nothing, because the entity is already managed. So the rule is simple: for entities loaded in the current transaction, change them and let the flush write them. We only need persist or save for new entities, and merge for detached ones.

3When an Automatic Flush Happens

The default flush mode is FlushModeType.AUTO. Under AUTO, Hibernate flushes at two moments. The first is just before the transaction commits, so that everything we changed reaches the database. The second is just before running a query whose results could be affected by pending changes. Imagine we change a product's price and then run a JPQL query for products under 15: if Hibernate did not flush first, the database would answer from the old price, and the query would contradict the object we hold in memory.

Java
Product p = em.find(Product.class, 1L); // select
p.setPrice(new BigDecimal("12.00"));
List<Product> cheap = em.createQuery(
"select p from Product p where p.price < 15", Product.class)
.getResultList();
// update product set ... where id=1 <- auto flush, the query reads the product table
// select ... from product where price < 15
em.createQuery("select c from Customer c", Customer.class).getResultList();
// select ... from customer <- no flush needed: no pending change touches customer

For JPQL and HQL queries Hibernate knows which tables the query reads, so it flushes only when pending changes touch those tables. For native SQL queries it cannot know which tables are involved, so through the JPA API it flushes before them to be safe (the exact rules for native queries differ between Hibernate versions, so check your version). Either way, the cost is a dirty check of the persistence context before the query, which matters when many entities are managed.

4Calling flush() Ourselves

We can call em.flush() at any point. It runs the same process immediately. We do this when we need the database to see our changes before something else happens: a native query or a stored procedure that reads the rows, a constraint we want to fail here with a clear error rather than at commit, or a batch job that flushes and then clears every few hundred entities to keep memory flat.

Java
em.persist(order);
em.flush(); // insert into orders ... (sent now, still not committed)
// a rollback here would undo the insert; other transactions cannot see it yet

5FlushModeType.COMMIT and Hibernate's Own Modes

JPA defines a second mode, FlushModeType.COMMIT, set with em.setFlushMode(FlushModeType.COMMIT) or per query. Under COMMIT, the specification only requires a flush at commit, so queries may not see our pending changes. That saves the dirty checks before queries, at the price of possibly stale query results within the transaction.

Hibernate's native API adds two more modes on Session: MANUAL, where nothing flushes unless we call flush(), and ALWAYS, which flushes before every query. MANUAL matters because Spring uses it for @Transactional(readOnly = true) with Hibernate, which is why changes made in a read-only transaction are not written.

Flush modes
ModeFlushes before commitFlushes before queries
AUTO (JPA default)yeswhen pending changes could affect the result
COMMIT (JPA)yesnot required by the spec
MANUAL (Hibernate)no, only on flush()no
ALWAYS (Hibernate)yesbefore every query

6Follow-up questions

Does dirty checking compare every field even when only one changed?

Yes, by default. Hibernate does not know which setter was called, so at each flush it compares every attribute of every managed entity with its snapshot. Bytecode enhancement with dirty tracking changes this: the entity records which attributes were set, and Hibernate checks only those.

Does flush() make the change visible to other transactions?

No. flush() sends the SQL inside the current transaction. Under the usual READ COMMITTED isolation, other transactions see the change only after commit, and a rollback undoes it.

Why did an UPDATE appear in the logs right before my SELECT?

That is the AUTO flush. A pending change touched a table the query reads, so Hibernate flushed it first to keep the query consistent with the objects in memory.

7Conclusion

In this answer, we saw that dirty checking compares every managed entity with the snapshot taken at load time and writes an UPDATE for each one that changed, which is why managed entities need no save() call. Under the default AUTO mode, Hibernate flushes before commit and before queries whose results could be affected, flush() sends SQL without committing, and COMMIT mode flushes only at commit. Hibernate's MANUAL mode, which Spring uses for read-only transactions, flushes only when asked.

What to say in the interviewAbout 90 seconds aloud

Open with

Dirty checking is how Hibernate detects changes without us telling it. When it loads an entity, it keeps a snapshot of the loaded values. At flush time it goes through every managed entity, compares the current attribute values with the snapshot, and generates an UPDATE for each entity that differs.

Then, if they want more

That is why for an entity loaded in the current transaction I just call the setter; calling save is unnecessary. Save or persist is for new entities, merge for detached ones.

As for when the flush happens: with the default JPA flush mode, AUTO, Hibernate flushes right before the transaction commits, and also right before a query whose results could be affected by pending changes.

For JPQL it knows the tables the query touches and flushes only if pending changes overlap; for native SQL it cannot know, so it tends to flush before them.

I can call flush explicitly when I need the database to see changes early, for example before a native query or to surface a constraint violation, but flush only sends SQL inside the transaction; it does not commit.

There is also FlushModeType.COMMIT, which flushes only at commit and skips the pre-query checks, and Hibernate's MANUAL mode, which Spring uses for read-only transactions. One practical point: dirty checking cost grows with the number of managed entities, so loading thousands of entities in one transaction makes every flush expensive.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is dirty checking in Hibernate, and when does a flush happen by default?": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/d5faf38888/