简体   繁体   中英

Spring - Transaction should commit in one method but should rollback in other methods which does a DB transaction

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 ie 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..?

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.

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