In this article, we are going to see how we can override the default FlushMode used by Hibernate.
If you bootstrap Hibernate natively, and not as a JPA provider, de default
FlushMode.AUTO is used which, as explained in
this article, does not trigger a Persistence Context flush prior to executing a native SQL query.
Hibernate default FlushMode AUTO
Assuming we have no
Post entity in our database:
"select count(p) " +
"from Post p")
If we persist a
"High-Performance Java Persistence"
and we bootstrap Hibernate natively using the
SessionFactoryBuilder, then the default
FlushMode.AUTO will not trigger a Persistence Context flush when a native SQL query is executed:
"select count(*) " +
This behavior only happens if Hibernate is bootstrap using the
SessionFactory class. We can see that flush is delayed until the Hibernate transaction is about to commit:
CALL NEXT VALUE FOR
-- o.h.e.t.i.TransactionImpl - committing
INSERT INTO post (
'High-Performance Java Persistence',
When using JPA, the Persistence Context is flushed on every query execution, be it JPQL, Criteria API or a native SQL query.
How to manually override the default Hibernate Session FlushMode
You can override the default
FlushMode either at the
If you are only interested in changing the
FlushMode only for the duration of the currently executing query, then you can do that as illustrated in the following example:
"select count(*) " +
FlushMode.ALWAYS mode instructs Hibernate to behave just like the JPA
FlushModeType.AUTO mode, therefore, triggering a Persistence Context flush prior to any query, be it JPQL, Criteria API or a native SQL query.
If you want to override the
FlushMode for every query executed by the current Hibernate
Session, then you can change the
FlushMode as follows:
However, this would require you to manually set the
FlushMode.ALWAYS for every
Session, which is not very convenient for the application developer.
How to automatically override the default Hibernate Session FlushMode
You can define a specific
FlushMode at the Hibernate configuration level using the
org.hibernate.flushMode configuration property:
<property name="org.hibernate.flushMode" value="ALWAYS" />
This way, every
Session will use the
ALWAYS flush strategy, so we don’t need to manually override the default
AUTO flush mode at the
I'm running an
on the 14th of May about The Best Way to Fetch Data with Java Persistence and Hibernate.
If you enjoyed this article, I bet you are going to love my
and Book as well.
FlushMode.ALWAYS strategy is desirable when bootstrapping Hibernate natively either via the Spring
SessionFactriyBuilder or the Hibernate
This way, you provide read-your-writes consistency guarantee, and native SQL queries will include any pending modifications that were scheduled to be executed at flush time.