Hibernate 6 does not auto flush when calling Query.stream() with NativeQuery
Description
Activity

Jean-Francois Fournier April 20, 2023 at 10:41 AM
Hello, thanks for creating a test case.
Oops, it seems you used entityManager.createQuery
instead of entityManager.createNativeQuery
in the second part of both test. Turns out the sql is the same for a native query and a HQL query. If you change it to createNativeQuery, the first test will fail.
thank you

Andrea Boriero April 20, 2023 at 9:23 AM
Hi ,
i created a test and it passes, am I missing somethig?

Andrea Boriero April 20, 2023 at 8:29 AM
Hi ,
I’m going to give a look at it.
Thanks

Jean-Francois Fournier April 19, 2023 at 3:09 PM
Hello,
If you look at the documentation here :
it says that it will flush the session if you use the entityManager to create the query. If you use the session to create the query it will not flush.
In your test you use the session instead of the entityManager to create the query. That’s why it’s not flushing in hibernate 5. If you use the entityManager it would flush.
Thank you
Extracted from the link above :
When executing a native SQL query, a flush is always triggered when using the EntityManager
API.
Example 414. Automatic flushing on native SQL using EntityManager
If you bootstrap Hibernate natively, and not through Jakarta Persistence, by default, the Session
API will trigger a flush automatically when executing a native query.
Example 415. Automatic flushing on native SQL using Session
To flush the Session
, the query must use a synchronization:
Example 416. Automatic flushing on native SQL with Session
synchronization

Andrea Boriero April 19, 2023 at 2:58 PMEdited
Hi ,
with native query Hibernate does not flush the session neither in 5 nor in 6, if you use HQL queries you’ll see the test passes
Calling query.stream() doesn’t auto flush the persistence context. Calling query.list() does flush the persistence context. This seems to be a bug as it was working with both methods in hibernate 5.
If we use the exemple found in
And tweak it a bit to use stream(), it won’t work. (but works in hibernate 5)
But it works if it uses list() instead
I look into the source a bit and
AbstractSelectionQuery
.stream()
doesn’t callbeforeQuery();
likeAbstractSelectionQuery.list()
do. SoNativeQueryImpl
.prepareForExecution()
is never called when usingstream()
.Thank you