A Hibernate Session May Get Flushed When Executing Queries

Today I noticed this Hibernate stactrace:

 at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:1185)
 at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1261)
 at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)

This means that when calling Query#list() (same goes for the JPA variant, which simply invokes the hinbernate class), the session might be flushed. That actually makes sense, because you may have:

//running transaction
session.save(foo);
List result = session.createQuery("from Foo").list();

This will return the newly inserted foo only if the session gets flushed. Otherwise the changes will not be reflected in the database, and you will not get your newly inserted entity. But when will the session be flushed? If we look at SessionImpl#autoFlushIfRequired(..):

  • “detect in-memory changes, determine if the changes are to tables named in the query and, if so, complete execution the flush”. That’s clever.
  • you need a running transaction

Something that’s nice to know, so that you don’t flush the session manually in case you need fresh query results.

Today I noticed this Hibernate stactrace:

 at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:1185)
 at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1261)
 at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)

This means that when calling Query#list() (same goes for the JPA variant, which simply invokes the hinbernate class), the session might be flushed. That actually makes sense, because you may have:

//running transaction
session.save(foo);
List result = session.createQuery("from Foo").list();

This will return the newly inserted foo only if the session gets flushed. Otherwise the changes will not be reflected in the database, and you will not get your newly inserted entity. But when will the session be flushed? If we look at SessionImpl#autoFlushIfRequired(..):

  • “detect in-memory changes, determine if the changes are to tables named in the query and, if so, complete execution the flush”. That’s clever.
  • you need a running transaction

Something that’s nice to know, so that you don’t flush the session manually in case you need fresh query results.