DEV Community

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

Posted on

5 1

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
  • COMMIT

Hibernate has

  • AUTO
  • COMMIT
  • MANUAL
  • ALWAYS

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay