Flush in Hibernate

Author Avatar
Learn Here Fun Pedia
5 min read •

flush()

Now for the main topic. When you call entityManager.flush();, it means: Synchronize the current persistence-context state with the database.

Suppose you have the following code:

Employee employee = entityManager.find(Employee.class, 101L);
employee.setSalary(60000);

At this point, the Java object has salary = 60000, but the Database still has salary = 50000. The persistence context knows the old state and the new state.

When flush occurs:

flush()
   ↓
Dirty checking
   ↓
Generate UPDATE
   ↓
Send SQL to DB

Potential SQL executed: UPDATE employee SET salary = 60000 WHERE id = 101;

1. Flush Does NOT Mean Commit

This distinction is extremely important. flush() and commit() are different operations.

  • Flush: Synchronizes ORM state with the database. (SQL sent to database).
  • Commit: Completes the database transaction. (Transaction finalized).

2. Example: Flush vs Commit

Imagine this transactional flow:

@Transactional
public void process() {
    employee.setSalary(60000);
    entityManager.flush();
    // more work...
}

After flush();, the UPDATE can already have been sent to the database. But the transaction is still active.

Transaction
   |
   ├── UPDATE sent (flush)
   |
   ├── more operations
   |
   └── commit

If something later causes the transaction to roll back (e.g., an exception during "more work..."):

flush
 ↓
UPDATE
 ↓
later error
 ↓
ROLLBACK

The transaction's changes are rolled back according to normal transaction semantics. So: Flush sends/synchronizes changes; commit makes the transaction successful/final.

3. Easy Memory Technique

Remember this simple breakdown:

  • FLUSH = Synchronize ("Send my pending changes.")
  • COMMIT = Finalize ("Make this transaction successful.")

4. When Does Hibernate Flush?

Hibernate can flush automatically depending on the flush mode and operation. For example, before certain queries, Hibernate may need to synchronize pending changes so that the query sees the appropriate database state.

employee.setSalary(60000);

entityManager.createQuery(
    "SELECT e FROM Employee e"
).getResultList();

Hibernate may flush before executing the query. This is one reason SQL can appear in logs at a point where you didn't explicitly call flush();.

5 & 6. Flush Modes

The two important JPA flush modes are AUTO and COMMIT.

Flush Mode Behavior
FlushModeType.AUTO The normal/default behavior. Hibernate decides when flushing is necessary, especially before queries that could be affected by pending changes.
FlushModeType.COMMIT Tells the persistence provider to prefer flushing at transaction completion, rather than automatically before every potentially relevant query.

7. Flush Timeline

Understand this timeline very well:

@Transactional
       |
       ↓
Transaction begins
       |
       ↓
Load entity
       |
       ↓
Modify entity
       |
       ↓
Persistence Context contains pending change
       |
       ↓
flush()
       |
       ↓
SQL sent
       |
       ↓
Transaction commit / commit()

Interactive Look: Flush vs Commit Timeline

To fully grasp the difference, step through this interactive visualization showing how data moves from memory, to the database buffer (flush), and finally gets permanently written (commit).

diagram Idea: A step-by-step state machine showing the timeline of a transaction, distinguishing exactly when dirty checking, flushing (SQL generation), and committing happen. Visual type: Sequence/State Diagram Data specification: - Data structure: Sequential steps in a transaction lifecycle. - Initial values: Steps: 1. Transaction Begins 2. Load Entity (DB -> Persistence Context) 3. Modify Entity (In Memory only) 4. Flush (Dirty Checking -> SQL Sent to DB Buffer) 5. Commit (DB Buffer -> Permanent Storage) - Mapping: Steps map to a visual timeline or flowchart. User controls: "Next Step" and "Previous Step" buttons to walk through the transaction. Interactivity: Stepping through the timeline highlights the current state of the "Java Memory (Persistence Context)" versus the "Database". Animation: Highlight flows from Memory to DB during the Flush step, and a final "Lock/Success" animation during the Commit step.

T3 Interview Summary

If the interviewer asks: "What is the difference between flush() and commit()?"

"flush() synchronizes the in-memory state of the Persistence Context with the database by generating and sending SQL statements (like UPDATEs or INSERTs) based on dirty checking. However, the database transaction remains open. commit() finalizes the database transaction, making those synchronized changes permanent. If a failure occurs after a flush but before a commit, the flushed SQL statements will still be rolled back."

Important Interview Questions (FAQs)

Q1: Does flush() write data permanently to the database?

No. flush() sends the SQL commands to the database, but those commands are executed within the context of the current transaction. They are not permanent until commit() is called.

Q2: Why do I see SQL statements executing before my transaction finishes?

This is due to FlushModeType.AUTO. Hibernate automatically flushes pending changes to the database before executing certain queries to ensure that the query results are accurate and reflect any in-memory modifications you've made.

Q3: What happens if an exception is thrown after flush() but before commit()?

The transaction will be rolled back. Even though flush() sent the SQL (e.g., an UPDATE statement) to the database, the active transaction guarantees atomicity. The database will discard those flushed changes.

Comments (0)