如何阅读 - 当被请求时 - 仅提交JPA(避免刷新实体)

时间:2016-09-01 09:49:17

标签: hibernate jpa osgi jta read-committed

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

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

将flushmode设置为'COMMIT'它不是我正在寻找的东西,因为我只想读取DB而不是刷新实体 - 在某些情况下,比如调用这个'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,但我认为这应该不重要

1 个答案:

答案 0 :(得分:0)

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

方法的实施:     List entitiesCommited = 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; 
}