java - 批量更新缓存问题? hibernate/集成测试/内存数据库/

标签 java hibernate jpa bulk

对于我的集成测试,我使用 HSQLDB-Inmemory。

当我通过 jql 查询执行批量更新时,我无法获得更新后的结果。

实体类

@Entity
public class Entity {
   private Long id;
   private String someCriteria;
   private Boolean changed = Boolean.FALSE;

   @Id
   @Column (name = "ID")
   public Long getId() {
      return id;
   }

   @Column (name = "SOMECRITERIA")
   public String getSomeCriteria() {
      return someCriteria;
   }

   @Column (name = "CHANGED")
   @Type (type = "yes_no")
   public String isChanged() {
      return changed;
   }

   […]
}

DataStore.class [...]

@Transactional
updateChangedMethod() {
Query query = entityManager.get().createQuery(“UPDATE Entity e SET e.changed = true WHERE (d.someCriteria = ‘true’) ");
query.executeUpdate();
}

@Transactional
selectAllMethod() {
Query query = entityManager.get().createQuery("Select e from Entity e", Entity.class);
}
[…]

服务类

 execute(){
        updateChangedMethod() ;
        selectAllMethod(); // Results do not contain the update
    }

当我显式地为​​每个实体执行刷新时,选择将按预期工作:

 @Transactional
    refresh(){
    Query query = entityManager.get().createQuery("Select e from Entity e",  Entity.class);
    List<Entity> result = query.getResultList();

    for (Entity entity : result) {
        entityManager.get().refresh(entity);
    }
    }


   execute(){
            updateChangedMethod() ;
            refresh();
            selectAllMethod(); // Results do contain the update
      }

我正在使用 Hibernate v 5.1.0.Final 和 HSQLDB v 2.3.4。 我认为这是一个缓存问题,有没有办法直接接收预期结果,而不需要对每个实体调用刷新?

最佳答案

The persistence context is not updated to reflect the results of the bulk operation. Bulk operations are issued as SQL against the database, bypassing the in-memory structures of the persistence context.

您可以通过三种方式从实体管理器获得最新结果:

  • 刷新实体
  • 清除实体管理器中的所有缓存并强制其从头开始更新所有内容
  • 通过添加使批量操作在自己的事务中运行 @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) 到方法签名。 (我不确定在spring中会如何实现,可能是@Transactional(propagation = Propagation.REQUIRES_NEW))

关于java - 批量更新缓存问题? hibernate/集成测试/内存数据库/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38844914/

相关文章:

java - 当我们需要多个 EntityManager 时?

java - 可用的 d-bus java 实现

java - 问题跟踪程序 - ArrayList 中的对象

java - 为什么此代码将结果加 1?

hibernate - 获取按列排序的惰性列表

java - jpa 中的可空 Map 映射

java - 为什么我的日志被删除?

mysql - 服务器端 Spring + Freemarker + Hibernate(EM) + MySql UTF-8 字符

java - 如何从外部id获取主键作为外键引用?

java - Spring JpaRepository - 分离和附加实体