我最近遇到了一个问题,即在执行 native SQL 查询之前,hibernate session 没有被刷新。创建 session 的刷新模式是AUTO。对于实体A,代码如下
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();
问题是我在 count(*)
查询中得到了错误的结果,因为在执行查询之前 session 没有被刷新。如果我这样做
session.flush();
在 count(*)
查询之前,它就可以正常工作。这与我从 https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#flushing-auto 中读到的相反其中指出
the Session API will trigger a flush automatically when executing a native query.
我可能会错过什么?
最佳答案
其实根据provided documentation它按预期工作。有两个带有 Session
的示例。第一个是示例 359。使用 session 自动刷新 native SQL 它有两个断言。请注意,第二个断言将 0
与预期值进行比较。第二个示例是示例 360。使用 session 同步自动刷新 native SQL,其中第二个断言的预期值为 one
。因此,为了实现您的预期行为,您必须启用同步,如图所示
关于java - Hibernate Session 在 native sql 查询之前没有被刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55704433/