Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 39 ยท Configuration and Sessions

Flush and Dirty Checking

Learn when Hibernate sends SQL, how dirty checking finds changed entities, the flush modes AUTO, COMMIT and MANUAL, the order of statements and how to tune updates.

When you call persist, remove or a setter on a managed entity, Hibernate usually does not talk to the database yet. It remembers what needs to happen, and sends the SQL later, at flush time. Knowing when flushing happens explains why exceptions appear at commit instead of at the offending line, why queries see your pending changes, and why changing the order of your calls does not change the order of the SQL.

This lesson covers flushing, dirty checking, flush modes and the statement order. Real Hibernate code is read-only; the stand-ins model the mechanism in plain Java.

What a flush is

A flush synchronizes the persistence context with the database: Hibernate walks the managed entities, finds the changes, and executes the pending INSERT, UPDATE and DELETE statements. A flush does not commit. The data becomes permanent only at commit; a flush inside a transaction that later rolls back is undone with it.

Hibernate flushes:

  1. Before a transaction commits.
  2. Before a query runs that could be affected by pending changes (in AUTO mode).
  3. When you call session.flush() explicitly.
Java
sessionFactory.inTransaction(session -> {
    Book book = session.find(Book.class, 1L);
    book.setTitle("New title");                 // nothing sent yet

    List<Book> books = session
        .createSelectionQuery("from Book b where b.title = 'New title'", Book.class)
        .getResultList();                       // AUTO flush: the UPDATE runs first, so this finds it
});

Dirty checking

When an entity is loaded, Hibernate stores a snapshot of its property values. At flush it compares each managed entity's current values with the snapshot. Entities that differ are dirty and get an UPDATE.

Java
Book book = session.find(Book.class, 1L);
book.setPages(book.getPages());      // same value: not dirty, no UPDATE
book.setPages(500);                  // different: UPDATE at flush

Two consequences worth remembering:

  • With many managed entities, flushes get expensive (the check is linear), another reason for short sessions and clear() in batch jobs.
  • By default the UPDATE lists all columns, not only the changed ones. If that bothers you (wide tables, triggers), add Hibernate's @DynamicUpdate to the entity:
Java
@Entity
@org.hibernate.annotations.DynamicUpdate     // UPDATE only the changed columns
public class Book { ... }

For data that never changes, @org.hibernate.annotations.Immutable tells Hibernate to skip the snapshot comparison for that entity entirely. For queries that load data you only read, setReadOnly(true) on the query (or Session.setDefaultReadOnly(true)) avoids the snapshots as well.

The order of statements

You might write remove(a), then persist(b), then change c. Hibernate does not run them in that order. It collects the actions into an action queue and executes them in a fixed order designed to respect constraints:

  1. Orphan removals
  2. Entity insertions
  3. Entity updates
  4. Collection removals, updates and insertions
  5. Entity deletions

Deletions come last so you can delete a parent after its children without violating foreign keys, and insertions first so new rows exist before updates point to them. A side effect: if you delete a row and insert another with the same unique value in the same flush, the insert can run before the delete and violate the unique constraint. The usual fix is an explicit session.flush() between the two.

flowchart LR
    A["Your calls<br/>remove(a), persist(b), setX(c)"] --> B["Action queue"]
    B --> C["INSERT b"]
    C --> D["UPDATE c"]
    D --> E["DELETE a"]

The SQL order is Hibernate's, not yours.

Flush modes

FlushMode controls when automatic flushing happens:

Mode Behavior
AUTO (default) Flush before commit and before queries that touch affected tables
COMMIT Flush only at commit (queries may not see pending changes)
ALWAYS Flush before every query
MANUAL Flush only when you call flush() (never automatic)
Java
session.setHibernateFlushMode(FlushMode.MANUAL);   // Hibernate-specific
// or, with the JPA API:
entityManager.setFlushMode(FlushModeType.COMMIT);

MANUAL is useful for read-only work where you want a guarantee that nothing is written, and for rare batch cases where you control the flush points. Most applications never need to leave AUTO.

Stand-in: the action queue

This stand-in records actions in the order you call them, then flushes them in Hibernate's order: inserts, updates, deletes. Notice that the printed SQL order differs from the call order.

Java Stand-in: flush order

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.

Stand-in: auto-flush before a query

If a query ran against the database while your changes were still pending, it would return stale data. In AUTO mode Hibernate flushes first; with COMMIT it does not. This stand-in keeps a pending-writes buffer and lets you choose the mode, so you can see the difference in what the query returns.

Java Stand-in: AUTO versus COMMIT

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.

Practical advice

  • Expect constraint violations at flush or commit time, not at the line that caused them. Call flush() in tests when you want the failure to appear where you changed the data.
  • Call flush() and then clear() every N entities in big batch jobs to keep the persistence context small.
  • If a unique constraint fails on "delete then insert", flush after the delete.
  • Do not compensate for a missing transaction by calling flush(); flush is not commit.
  • Do not call flush() in a loop to "see" changes; queries already flush in AUTO mode.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a flush do?

    A flush synchronizes the persistence context with the database. The data stays uncommitted until the transaction commits.
  2. 2. How does Hibernate find which entities need an UPDATE?

    That comparison is dirty checking.
  3. 3. In which order does Hibernate send statements at flush?

    The action queue has a fixed order so constraints are respected: inserts, updates, collection operations, then deletes.
  4. 4. Which FlushMode never flushes automatically?

    MANUAL flushes only when you call flush(). COMMIT flushes at commit.
  5. 5. What does @DynamicUpdate change?

    By default UPDATE sets all columns; @DynamicUpdate generates SQL for the changed ones only.

Summary

  • Hibernate delays SQL until flush: before commit, before affected queries (in AUTO), or on flush().
  • Dirty checking compares managed entities with load-time snapshots.
  • Statements run in a fixed order: inserts, updates, collection changes, deletes, regardless of your call order.
  • FlushMode is AUTO by default; COMMIT and MANUAL reduce or remove automatic flushes.
  • flush() plus clear() keeps big batches light; @DynamicUpdate and @Immutable tune updates.

Next: Schema Generation and Naming