我正試圖圍繞事務管理進行討論,但我很難弄清楚如何從事務回滾中恢復並繼續提交新事務。下面的代碼是什麼,我試圖做一個簡化版本:如何回滾事務並繼續處理更新?
@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?
}
}
}
感謝您的回答!因此,如果任何異常用'@ApplicationException(rollback = t rue)'在調用'this.myBean1.process(obj)'期間被拋出;',事務將被容器回滾並且我可以吞下/記錄異常?然後,在下次調用this.myBean1.process(obj)時,容器會創建一個新的事務;當我們遍歷objs列表時, –