简体   繁体   中英

How to wrap multiple JPA EntityManager persist/merge into single transaction

I need to update several tables in a single transaction.

Currently, I have the following structure in my code:

(pseudo-code)

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++;
}

Question: How do I wrap the persistTable1 (which will always get called once - no matter what), and the persistTable2 call (which will get called 0 to n times) into a single transaction, so that if any persist/merge fails then everything will get rolled-back?

The persist/update code is using JPA EntityManager.

You can use the transactional context in the method caller.

@Transactional(propagation = Propagation.REQUIRES_NEW)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM