0

How to handle Spring Transaction in Java where I have a scenario :

A service method let's say methodA() calls another method - methodB(). From methodB(), I am doing a validation and if that validation turns true, I will call another methodC() and this method must get committed, whereas all other methods should get rollback i.e. the transactions done from methodA() and methodB() must get rollback but transaction in methodC must be committed and it must not be rollback.

For rollbacking the transaction I use -

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

Real-time scenario -

When I perform a transaction, I try to create some transactions. Based on those transactions, I check if one of the value has reached threshold point, I need to trigger a mail. This mail is a DB transaction. All other transactions must be rollbacked and only the mail transaction must be persisted.

Any help appreciated.

EDIT: -

Similar question -

commit changes in try-catch inside @Transactional

But this doesnot solve my prblem. what if the @Transactional is given at Class Level and method level too..?

Ashfaque Rifaye
  • 1,041
  • 3
  • 13
  • 22

1 Answers1

0

in my opinion,code like this

@Transactional(propagation= Propagation.REQUIRED)
public void methodA() {
    methodB();
}

public void methodB() {

    if(validtaion=true){
        SeverB.methodC();
        throw YourException;
    }
}

// in ServerB.java
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void methodC() {
    // do your thing
}

and,you'd better test whether it work well.

jin
  • 430
  • 2
  • 9
  • I have tried using this approach but still this doesn't work out well. there is a class level @Transaction where I call methodC(). Maybe this acts as a hinder I guess. Not sure how to tackle this problem :( – Ashfaque Rifaye May 13 '19 at 10:11
  • in order to make the aop work.you need put add @Transactional in another class.methodB and methodC are not in the same class. – jin May 13 '19 at 10:17
  • Tried using @Transactional in another class - of methodC(). – Ashfaque Rifaye May 13 '19 at 10:19
  • i run my test case ,it works. one thing you need focus on the first method which you call. this method put the @Transactional. – jin May 13 '19 at 10:33