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 https://docs.jboss.org/hibernate/orm/6.1/userguide/html_single/Hibernate_User_Guide.html#_auto_flush_on_native_sql_query
assertTrue(((Number) entityManager
.createNativeQuery("select count(*) from Person")
.getSingleResult()).intValue() == 0);
Person person = new Person("John Doe");
entityManager.persist(person);
assertTrue(((Number) entityManager
.createNativeQuery("select count(*) from Person")
.getSingleResult()).intValue() == 1);
And tweak it a bit to use stream(), it won’t work. (but works in hibernate 5)
assertTrue(entityManager
.createNativeQuery("select name from Person where name ='John Doe'")
.getResultList().size() == 0);
Person person = new Person("John Doe");
entityManager.persist(person);
assertTrue(entityManager
.createNativeQuery("select name from Person where name ='John Doe'")
.getResultStream().toList().size() == 1);
But it works if it uses list() instead
assertTrue(entityManager
.createNativeQuery("select name from Person where name ='John Doe'")
.getResultList().size() == 0);
Person person = new Person("John Doe");
entityManager.persist(person);
assertTrue(entityManager
.createNativeQuery("select name from Person where name ='John Doe'")
.getResultList().size() == 1);
I look into the source a bit and AbstractSelectionQuery.stream() doesn’t call beforeQuery(); like AbstractSelectionQuery.list() do. So NativeQueryImpl.prepareForExecution() is never called when using stream(). Thank you |