我正在尝试围绕事务管理进行思考,但我很难弄清楚我应该如何从事务回滚中恢复并继续提交新事务。下面的代码是我正在尝试做的简化版本:
@Stateless
public class MyStatelessBean1 implements MyStatelessLocal1 {
@EJB
private MyStatelessLocal1 myBean1;
@TransationAttribute(TransactionAttributeType.NEVER)
public void processObjects(List<Object> objs) {
// this method just processes the data; no need for a transaction
for(Object obj : objs) {
// If the call to process results in the transaction being rolled back,
// how do I rollback the transaction and continue to iterate over objs?
this.myBean1.process(obj);
}
}
@TransationAttribute(TransactionAttributeType.REQUIRES_NEW)
public void process(Object obj) {
// do some work with obj that must be in the scope of a transaction
}
}
如果在对 的调用中发生事务回滚process(Object obj)
,则会引发异常,objs
并且不会迭代中的其余对象,也不会提交任何更新。如果我想回滚发生错误的事务,但继续迭代objs
列表,我应该怎么做呢?如果我只是捕获下面代码中的异常,我需要做些什么来确保事务回滚吗?
public void processObjects(List<Object> objs) {
// this method just processes the data; no need for a transaction
for(Object obj : objs) {
// If the call to process results in the transaction being rolled back,
// how do I rollback the transaction and continue to iterate over objs?
try {
this.myBean1.process(obj);
} catch(RuntimeException e) {
// Do I need to do anything here to clean up the transaction before continuing to iterate over the objs?
}
}
}