DEV Community

Cover image for Hibernate - Flush
Yiğit Erkal
Yiğit Erkal

Posted on


Hibernate - Flush

One of the most confusing points about JPA/Hibernate is the flush operation and its relation to the transaction.

Flush is the operation that transfers the changes related to the existing entities to the database with SQL statements in the PersistenceContext managed via Session in Hibernate and EntityManager in JPA.

Transaction, on the other hand, ensures that persistence operations (insert, update or delete) performed in the database between the beginning and the end (commit) become permanent with the “all-or-nothing” logic.

When working with JPA/Hibernate, the SQL equivalents of persist, merge, and remove/delete operations on the PersistenceContext are not immediately reflected in the DB. These changes are accumulated in the PersistenceContext. This is called the transactional write behind feature of the ORM.

These accumulated changes are reflected to the DB with the flush operation. However, in order for these changes to become permanent, the current transaction must be successfully terminated (commit).

Do I need flush after every operation? 💧

Flush operation is run automatically in the background when the transaction is committed under normal conditions. Normally there is no need to run a manual flush on the PersistenceContext.

With FlushMode, you can control when the flush operation will run.

JPA has

  • AUTO

Hibernate has

  • AUTO

modes. By default, FlushMode is AUTO. In this case, the flush operation is automatically triggered immediately before the ORM queries run regarding the entities that have changed on the PersistenceContext and during the transaction commit.

To sum up
If the Flush method is run manually at any stage, changes on the PersistenceContext are detected and reflected in the database as INSERT, UPDATE, DELETE SQL statements. However, these changes can become permanent only if the transaction commits.

Top comments (0)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git