Introduction

Not all queries trigger a Session flush

Many would assume that Hibernate always flushes the Session before any executing query. While this might have been a more intuitive approach, and probably closer to the JPA’s AUTO FlushModeType, Hibernate tries to optimize that. If the currently executed query is not going to hit the pending SQL INSERT/UPDATE/DELETE statements then the flush is not strictly required.

As stated in the reference documentation, the AUTO flush strategy may sometimes synchronize the current persistence context prior to a query execution. It would have been more intuitive if the framework authors had chosen to name it FlushMode.SOMETIMES.

JPQL/HQL and SQL

Like many other ORM solutions, Hibernate offers a limited Entity querying language (JPQL/HQL) that’s very much based on SQL-92 syntax.

The entity query language is translated to SQL by the current database dialect and so it must offer the same functionality across different database products. Since most database systems are SQL-92-complaint, the Entity Query Language is an abstraction of the most common database querying syntax.

While you can use the Entity Query Language in many use cases (selecting Entities and even projections), there are times when its limited capabilities are no match for an advanced querying request. Whenever we want to make use of some specific querying techniques, such as:

Hibernate is a persistence framework. Hibernate was never meant to replace SQL. If some query is better expressed in a native query, then it’s not worth sacrificing application performance on the altar of database portability.

AUTO flush and HQL/JPQL

First we are going to test how the AUTO flush mode behaves when an HQL query is about to be executed. For this we define the following unrelated entities:

The test will execute the following actions:

A Person entity is going to be persisted.

Fetching a User entity should not trigger a Persistence Context flush.

Querying for the Person entity, the AUTO flush should trigger the entity state transition synchronization (an INSERT statement for the post table row should be executed prior to executing the SELECT query).

As you can see, the User select hasn’t triggered the Session flush. This is because Hibernate inspects the current query space against the pending table statements. If the currently executing query doesn’t overlap with the unflushed table statements, the flush can be safely ignored.

The reason why it works is because Entity Queries are parsed and translated to SQL queries. Hibernate cannot reference a non-existing table, therefore it always knows the database tables an HQL/JPQL query will hit.

So Hibernate is only aware of those tables we explicitly referenced in our HQL query. If the current pending DML statements imply database triggers or database level cascading, Hibernate won’t be aware of those. So even for HQL, the AUTO flush mode can cause consistency issues.

AUTO flush and native SQL queries

When it comes to native SQL queries, things are getting much more complicated. Hibernate cannot parse SQL queries because it only supports a limited database query syntax. Many database systems offer proprietary features that are beyond Hibernate Entity Query capabilities.

Querying the Person table, with a native SQL query is not going to trigger the flush, causing an inconsistency issue:

The newly persisted Product was only inserted during transaction commit because the native SQL query didn’t trigger the flush. This is major consistency problem, one that’s hard to debug or even foreseen by many developers. That’s one more reason for always inspecting auto-generated SQL statements.

Overruling the current flush strategy

Even if the current Session defines a default flush strategy, you can always override it on a query basis.

Query flush mode

The ALWAYS mode is going to flush the persistence context before any query execution (HQL or SQL). This time, Hibernate applies no optimization and all pending entity state transitions are going to be synchronized with the current database transaction.

Instructing Hibernate which tables should be synchronized

You could also add a synchronization rule to your current executing SQL query. Hibernate will then know what database tables need to be synchronized prior to executing the query. This is also useful for second level caching as well.

If you enjoyed this article, I bet you are going to love my Book and Video Courses as well.

Conclusion

The AUTO flush mode is tricky and fixing consistency issues on a query basis is a maintainer’s nightmare. If you decide to add a database trigger, you’ll have to check all Hibernate queries to make sure they won’t end up running against stale data.

My suggestion is to use the ALWAYS flush mode, since it’s closer to how JPA defines the AUTOFlushModeType.

Inconsistency is much more of an issue that some occasional premature flushes. While mixing DML operations and queries may cause unnecessary flushing this situation is not that difficult to mitigate. During a session transaction, it’s best to execute queries at the beginning (when no pending entity state transitions are to be synchronized) and towards the end of the transaction (when the current persistence context is going to be flushed anyway).

The entity state transition operations should be pushed towards the end of the transaction, trying to avoid interleaving them with query operations (therefore preventing a premature flush trigger).

Subscribe to our Newsletter

* indicates required

Email Address *

10 000readers have found this blog worth following!

If you subscribeto my newsletter, you'll get:

A free sampleof my Video Course about running Integration tests at warp-speed using Docker and tmpfs