【发布时间】:2011-07-03 08:26:24
【问题描述】:
目前我正在尝试应用程序管理的持久性上下文,方法是手动创建实体管理器并将它们存储以在 JSE 应用程序中启用跨越多个请求调用(可能类似于扩展持久性上下文)的事务。
但是,我想知道是否可以通过使用 spring 的 @PersistenceContext 注入并使用 @Transactional 注释标记方法以使用手动启动的事务来避免在整个服务和 DAO 方法中发送 entityManager 对象作为附加参数实体经理。
我想我可以通过为这个特性使用 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);
工具内部:
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);
}
以及服务方法的示例:
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) {
// ........
}
}
有没有办法做到这一点?
谢谢!
【问题讨论】: