Spring JPA:使用@Transactional和@PersistenceContext的应用程序管理持久化上下文

ber*_*tie 6 spring jpa jpa-2.0

目前我正在尝试应用程序管理的持久化上下文,通过手动创建实体管理器并将它们存储起来以启用跨越JSE应用程序中的多个请求调用(可能类似于扩展持久性上下文)的事务.

但是,我想知道我是否可以通过使用spring的@PersistenceContext注入来避免在整个服务和DAO方法中发送entityManager对象作为附加参数,并使用@Transactional注释标记方法以使用与该实体管理器手动启动的事务.

我想我可以通过使用ThreadLocal来管理这个功能,但我会更高兴能够将它附加到spring框架.

这是我想到的一个例子:


UI动作方法:

在这里我们可以看到事务是由ui逻辑启动的,因为后端没有外观/命令方法将这些调用分组到业务逻辑:

Long transactionid = tool.beginTransaction();

// calling business methods
tool.callBusinessLogic("purchase", "receiveGoods", 
                        paramObject1, transactionid);

tool.callBusinessLogic("inventory", "updateInventory", 
                        paramObject2, transactionid);

tool.commitTransaction(transactionid);
Run Code Online (Sandbox Code Playgroud)

在工具里面:

public Long beginTransaction() {
  // create the entity --> for the @PersistentContext
  Entitymanager entityManager = createEntityManagerFromFactory();
  long id = System.currentTimeMillis();
  entityManagerMap.put(id, entitymanager);

  // start the transaction --> for the @Transactional ?
  entityManager.getTransaction().begin();

  return id;
}

public void commitTransaction(Long transactionId) {
  EntityManager entityManager = entityManagerMap.get(transactionId);

  entityManager.getTransaction().commit();
}

public Object callBusinessLogic(String module, String function, 
                        Object paramObject, Long transactionid) {
    EntityManager em = entityManagerMap.get(transactionId);

    // =================================
    //        HOW TO DO THIS????
    // =================================
    putEntityManagerIntoCurrentPersistenceContext(em);

    return executeBusinessLogic(module, function, paramObject, transactionid);
}
Run Code Online (Sandbox Code Playgroud)

以及服务方法的示例:

public class Inventory {
  // How can i get the entityManager that's been created by the tool for this thread ?
  @PersistenceContext
  private EntityManager entityManager;

  // How can i use the transaction with that transactionId ?
  @Transactional
  public void receiveGoods(Param param) {
    // ........
  }
}
Run Code Online (Sandbox Code Playgroud)

反正有没有实现这个目标?

谢谢 !

Rob*_*bin 9

Spring对@PersistenceContext注释的处理几乎完全符合你的要求,但有一个很大的区别:你总是得到一个事务范围的EntityManager和Spring为同一个线程注入总是相同的实例,所以你有一种传播方式而不必担心线程安全.但是你永远不会以这种方式获得扩展的上下文!
相信我,Spring 3和扩展的持久化环境不能很好地结合在一起,也许这会在Spring 3.1中发生变化,但我担心这不是他们关注的焦点.如果你想使用扩展的持久化上下文,让Spring注入EntityManagerFactory(通过@PersistenceUnit注释),然后自己创建EntityManager.对于传播,您必须将实例作为参数传递或自己将其存储在ThreadLocal中.

  • `entityManagerFactory.createEntityManager()`创建一个新的_application-managed_实例,而`@PersistenceContext`注入一个_container-managed_实例.检查JPA规范的差异.在Spring框架的特定情况下,容器管理的实例具有作用域的事务并绑定到本地线程,因此每个线程最多同时具有一个实例.(所以不需要同步) (3认同)