用于长时间对话的 JavaEE EntityManager
JavaEE EntityManager for long conversation
实现此用例的最佳方法是什么?
Image 我有一个 EJB A
,它是一种顶级业务流程调用者。它调用其他 bean。如果在调用其他 bean 期间发生异常,那么我想回滚 A
.
所做的一切
我想在 A
bean 中注入 EntityManager 一次,然后将其传递给其他 bean。这被认为是一种好的做法?
按照此处所述使用容器管理事务:https://docs.oracle.com/cd/E16439_01/doc.1013/e13981/servtran002.htm。
在您的 A bean 上添加以下注释 class:@TransactionManagement(value=TransactionManagementType.CONTAINER)
以及 A 中调用其他 bean 的方法的以下注解:@TransactionAttribute(value=REQUIRED)
并确保其他 bean 将抛出异常以回滚事务。
这只是一个简单的用例,我强烈建议您阅读 EJB 事务管理。
示例:
@Stateless
public static class A{
@PersistenceContext(unitName="a")
private EntityManager em = null;
@Inject
private B b = null;
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void doInTransaction(){
//get some data from em
//modify and save back to b
b.save(data);
}
}
public static class B{
@PersistenceContext(unitName="a")
private EntityManager em = null;
public void save(data){
//save against em
//catch JPA exception and throw back as RuntimeException
}
}
实现此用例的最佳方法是什么?
Image 我有一个 EJB A
,它是一种顶级业务流程调用者。它调用其他 bean。如果在调用其他 bean 期间发生异常,那么我想回滚 A
.
我想在 A
bean 中注入 EntityManager 一次,然后将其传递给其他 bean。这被认为是一种好的做法?
按照此处所述使用容器管理事务:https://docs.oracle.com/cd/E16439_01/doc.1013/e13981/servtran002.htm。
在您的 A bean 上添加以下注释 class:@TransactionManagement(value=TransactionManagementType.CONTAINER)
以及 A 中调用其他 bean 的方法的以下注解:@TransactionAttribute(value=REQUIRED)
并确保其他 bean 将抛出异常以回滚事务。
这只是一个简单的用例,我强烈建议您阅读 EJB 事务管理。
示例:
@Stateless
public static class A{
@PersistenceContext(unitName="a")
private EntityManager em = null;
@Inject
private B b = null;
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void doInTransaction(){
//get some data from em
//modify and save back to b
b.save(data);
}
}
public static class B{
@PersistenceContext(unitName="a")
private EntityManager em = null;
public void save(data){
//save against em
//catch JPA exception and throw back as RuntimeException
}
}