1

我有一个使用NamedQuery. 我更新每个实体的值,然后运行另一个命名查询(以相同的方法和Transaction)过滤旧值,它返回相同的实体,就好像我没有更改它们一样。

我知道EntityManager需要刷新并且它应该自动发生,但这没有任何区别。

我启用了休眠 SQL 日志记录,并且可以看到当我调用刷新但容器事务提交时实体没有更新。

EntityManager entityManager = getPrimaryEntityManager();
MyEntity myEntity = entityManager.find(MyEntityImpl.class, allocationId);
myEntity.setStateId(State.ACTIVE);
// Flush the entity manager to pick up any changes to entity states before we run this query.
entityManager.flush();
Query countQuery = entityManager
        .createNamedQuery("MyEntity.getCountByState");
// we're telling the persistence provider that we want the query to do automatic flushing before this
// particular query is executed.
countQuery.setParameter("stateId", State.CHECKING);
Long count = (Long) countQuery.getSingleResult();
// Count should be zero but isn't. It doesn't see my change above
4

2 回答 2

1

老实说,我对 JPA 不是很熟悉,但是我在使用 Hiberate 的会话管理器时遇到了类似的问题。我的解决方法是在再次查询之前从 Hibernate 的会话中手动删除指定的对象,因此它被迫从数据库中进行查找并且不会从缓存中获取对象。您可以尝试对 JPA 的 EntityManager 执行相同的操作。

于 2009-06-02T17:11:55.903 回答
0

我刚刚遇到同样的问题并发现了两件事:

  • 首先,您应该检查持久性上下文和/或查询的 FlushMode。
  • 其次,确保实体管理器是事务管理和查询执行的完全相同的对象。就我而言,我在 entityManager 上有了 Mockito 间谍,这足以破坏事务管理。
于 2013-12-27T09:55:10.850 回答