0

据我所经历的,JPA/hibernate 将返回存在于数据库中或在事务期间被持久化然后刷新到数据库中的实体。

我希望某些查询能够按原样向 Hibernate 询问数据库,而不考虑任何活动事务、任何刷新的实体等。在这些特定情况下,我只想阅读它提交的内容。

将刷新模式设置为“提交”这不是我想要的,因为我只想按原样读取数据库 - 跳过刷新的实体 - 在某些情况下,例如调用此 'findCommittedEntities' 方法。

一个简单的代码,显示我在寻找什么:

@Transactional()
public void mySampler(){
    Entity ent=new Entity();
    entityManager.persist(ent)

    /*Here JPA/Hibernate configured with flushmode AUTO will flush the        
     *persisted entity to db. That's Perfect!
     */
    List<Entity> entities=service.findEntities() 
    //So this list should be of size 1 assuming we started with an empty DB of course!
    System.out.println(entities.size())

    //But I also would like to be able to read the DB as is:
    List<Entity> entitiesCommited=service.findCommittedEntities(...)

    //This should be of size 0 as transaction is not commited yet
    System.out.println(entitiesCommited.size())

}

那么我应该怎么做才能做到这一点呢?还是根本不可能?

至于我正在使用 OSGi 和 Aries JPA/JTA 的环境,但我认为这在这里无关紧要

4

1 回答 1

0

要回答我的问题,因为我已经找到了解决方案并期待可能对其他人有用:

方法的实现:ListentitiesCommited=service.findCommittedEntities(...)

应该是这样的:

//We require a new transaction
@Transactional(value = TxType.REQUIRES_NEW)
public Entity findCommitedEntities(..){

     /*This is important to create a new one. Because if we use the one we
      *are using in 'mySampler()' we would be running the query in the scope
      *of the other transaction and not the new one*/
      EntityManager newTxEm=emf.createEntityManager()

      //We join if it is not already to the new transaction
      newTxEm.joinTrasaction();
                [...]
         //  we execute whatever named query that gets all entities
                [...]
      return entities; 
}
于 2016-09-02T07:14:09.007 回答