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

Bulkupdate Cache issue? Hibernate / IntegrationTest / Inmemory DB /

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

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

Entity.class

@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);
}
[…]

Service.class

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

当我明确地为每个实体执行刷新时,select 按预期工作:

 @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))