【问题标题】:Make JPA persistence context recognize the changes made by bulk operations让 JPA 持久化上下文识别批量操作所做的更改
【发布时间】:2014-08-12 12:25:52
【问题描述】:

JPA 批量操作(例如 DELETEUPDATE)作为 SQL 对数据库发出。因此,不会更新持久性上下文以反映操作的结果。

例如更新所有员工的部门,持久化上下文中管理的实体的值不会更新:

entityManager.createQuery("UPDATE Employee e SET e.department = null").executeUpdate();

如何让持久化上下文识别批量操作所做的更改?

【问题讨论】:

    标签: java jpa


    【解决方案1】:

    我发现的最简单的方法是在批量操作后从EntityManagerFactory 的缓存中调用evictAll() 方法:

    entityManager.getEntityManagerFactory().getCache().evictAll();
    

    为了安全起见,建议在自己的事务中执行批量操作。

    【讨论】:

      【解决方案2】:

      您可以使用

      从数据库中重新加载实体及其关系

      entityManager.refresh(employeeInstance);

      请注意,Employee 的 department 属性必须在关系上指定 CascadeType.REFRESH

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-05-15
        • 1970-01-01
        • 2013-04-01
        • 2020-01-09
        • 1970-01-01
        • 2016-01-31
        • 2010-11-30
        相关资源
        最近更新 更多