为什么我看不到通过 Spring Data JPA 的更新查询发出的更改?

2022-01-18 00:00:00 spring java jpa spring-data

我有以下服务:

@Service
public class CamelService {

    @Transactional
    public aCamelThing() {

          Camel camel = this.camelRepository.findOne(1);

          System.out.println(camel.getCamelName());  // prints "normalCamel"

          // simple hql set field 'camelName'
          int res = this.camelRepository.updateCamelName(1,"superCamel!");

          Camel camelWithNewName = this.camelRepository.findOne(1);

          System.out.println(camelWithNewName .getCamelName());  // prints "normalCamel" ?!?!?

    } 
}

知道如何实现第二个 println 将打印的目标:superCamel!"?(将第二次调用与新事务分开并不理想).

Any idea how can i achieve the goal that the second println will print: "superCamel!" ? (separating the second call to a new transaction is not ideal).

推荐答案

您看到它工作的原因很简单:JPA 被定义为以这种方式工作.

The reason you see this working as it works is quite simple: JPA is defined to work that way.

我假设您触发了 updateCamelName(…) 的更新查询.JPA 规范为更新和删除操作规定了以下内容:

I am assuming you trigger an update query for updateCamelName(…). The JPA specification states the following for update and delete operations:

持久化上下文与批量更新或删除的结果不同步.

The persistence context is not synchronized with the result of the bulk update or delete.

在执行批量更新或删除操作时应小心,因为它们可能会导致数据库与活动持久性上下文中的实体之间的不一致.一般来说,批量更新和删除操作只能在新的持久性上下文中的事务内执行,或者在获取或访问状态可能受此类操作影响的实体之前执行.

这意味着,如果您需要查看此类操作的更改,您需要执行以下操作:

This means, that if you need to see the changes of such an operation you need to do the following things:

  1. 在此操作后清除 EntityManager. Spring Data JPA 的 @Modifying 注释有一个 clearAutomatically 标志,默认为.如果设置为 true,则调用查询方法将自动清除 EntityManager(顾名思义.请谨慎使用,因为它会有效地删除所有尚未刷新的待处理更改到数据库了!
  2. EntityManager 重新获取实体的新实例. 在存储库上调用 findOne(...) 似乎是一种合理的方式这样做,因为这大致转换为 EntityManager.find(...).请注意,这可能仍会影响持久性提供程序上配置的二级缓存.
  1. Clear the EntityManager after this operation. Spring Data JPA's @Modifying annotation has a clearAutomatically flag defaulting to false. If that is set to true, invoking the query method will clear the EntityManager automatically (as the name suggests. Use that with caution, as it will effectively drop all pending changes that have not been flushed to the database yet!
  2. Re-obtain a fresh instance of the entity from the EntityManager. Calling findOne(…) on the repository seems like a reasonable way to do this as this roughly translates into EntityManager.find(…). Be aware that this might still hit 2nd level caches configured on the persistence provider.

解决此问题的最安全方法是 - 正如规范所建议的那样 - 仅将更新查询用于批量操作,并在默认情况下回退到加载实体、更改、合并"方法.

The safest way to work around this is - as the spec suggests - to use update queries only for bulk operations and fall back to the "load entity, alter, merge" approach by default.

相关文章