Search code examples
javaspringtransactionsspring-transactions

Rolling Back a transaction from beforeCompletion TransactionSynchronization?


I am using Spring TransactionSynchronizationManager to register a beforeCompletion callback like below:

@Transactional
public void doTransaction() {
    //do DB stuff
    updateDB();

    //register a synchronization
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
        @Override
        public void beforeCompletion() {
            if(!isCallApiSuccessful()) {
                //rollback the transaction
            }
        }
    });
}

Question is how do I roll-back transaction from the beforeCompletion callback ? Would throwing an exception work?


Solution

  • Would throwing an exception work?

    No, it will not work because beforeCompletion() is for cleaning up resources.
    Here is what throwing an exception has as effect according to the documentation :

    Throws:

    java.lang.RuntimeException - in case of errors; will be logged but not propagated (note: do not throw TransactionException subclasses here!)

    You should probably implement void beforeCommit(boolean readOnly) to achieve that and throws an RuntimeException inside it if you want to prevent the commit.
    Here is what throwing an exception has as effect according to the documentation :

    Throws:

    java.lang.RuntimeException - in case of errors; will be propagated to the caller (note: do not throw TransactionException subclasses here!)