How to roll back transactions and continue processing updates?

I'm trying to wrap my head around transaction management, but it's hard for me to understand how I should recover from a transaction rollback and continue to make new transactions. The code below is a simplified version of what I'm trying to do:

@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 } } 

If a transaction is rolled back when calling process(Object obj) , then an exception is thrown, and the remaining objects in objs not repeated and are not updated. If I want to undo the transactions in which the error occurred, but keep sorting through the objs list, how should I do it? If I just catch the exception, as in the code below, do I need to do something to make sure the transaction is canceled?

 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? } } } 
+4
source share
1 answer

The processObjects call is in a (separate) transaction. You catch all RuntimeException s, divide these exceptions into two groups.

Group one: EJBException or any other exception annotated with @ApplicationException(rollback=true) container will return this exception to you.

Group Two: All other exceptions. (Basically, those exceptions that will not be automatically returned by the container :(). β†’ The transaction will not be rolled back if you do not.

To force a rollback you can always throw new EJBException ... etc.

Also note that after @ApplicationException(rollback=true) an Exception annotated with @ApplicationException(rollback=true) , the container will cancel the current transaction, if any (EJB-Beans is in the default transaction), regardless of what you do ( catch and ignore, for example) if the Bean is annotated with @TransactionManagement(TransactionManagementType.CONTAINER) , which is used by default in EJB.

+3
source

Source: https://habr.com/ru/post/1432145/


All Articles