2015-11-05 65 views
0

我需要在单个事务中更新多个表。如何包装多个JPA EntityManager持久化/合并到单个事务中

目前,我在我的代码的结构如下:

(伪代码)

process(updateList, mainObject); // returns list of objects and main business object to persist/update 
persistTable1(mainObject); // table 1 

int objectIndex = 0; 
while(objectIndex < updateList.size()) { 
    persistTable2(updateList[objectIndex]); // table 2 
    objectIndex++; 
} 

问题: 如何包裹persistTable1(这将永远被调用一次 - 不管什么)和persistTable2调用(将被调用0到n次)成一个事务,这样如果任何持续/合并失败,那么一切都会回滚?

持久性/更新代码正在使用JPA EntityManager。

+0

您使用容器管理事务吗?这可能有助于[链接](https://docs.oracle.com/javaee/5/tutorial/doc/bncij.html) – Thevenin

+0

基本上只是将代码放入具有活动事务的方法中。 – Thevenin

+0

@Thevenin - 是的,容器管理(TomEE)。我还应该提到这发生在一个REST风格的Web服务调用中(泽西岛)。这很重要吗? –

回答

0

您可以在方法调用方中使用事务性上下文。

@Transactional(propagation = Propagation.REQUIRES_NEW)

+0

这不适用于我的项目,因为它是容器管理,不使用Spring。 –