1
votes

I recently faced a problem where hibernate session is not getting flushed before executing a native SQL query. The flushmode of created session is AUTO. For the entity A, code is like

A a=aDao.getById(session,id);
  a.setB(3);
  ...
   String query = "select count(*) as total from A a where a.b=3";
   session.createSQLQuery(query)
             .addScalar("total", StandardBasicTypes.).uniqueResult();

The problem is I am getting wrong results with the count(*) query because session is not getting flushed before executing the query. If I do

session.flush();

before count(*) query, then it works just fine. This is contrary to what I have read from https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#flushing-auto which states that

the Session API will trigger a flush automatically when executing a native query.

What could I be missing ?

1

1 Answers

2
votes

Actually according to a provided documentation it works as expected. There are two examples with a Session. The first one is Example 359. Automatic flushing on native SQL using Session And it has two assertions. Note that the second assertion compares zero as expected value. And the second example is Example 360. Automatic flushing on native SQL with Session synchronization where second assertion has a one as expected value. So to achieve your expected behavior you must enable a synchronization as shown