简体   繁体   中英

Why Spring doesn't have rollback methods in TransactionSynchronization interface?

In Spring TransactionSynchronization interface it has methods (in order of execution):

- beforeCommit
- beforeCompletion
- afterCommit: Can perform further operations right after the main transaction has successfully committed. 
- afterCompletion

Why Spring doesn't have rollback methods, such as beforeRollback or afterRollback but it has for commit only (beforeCommit and afterCommit)? Will this is necessary? Can anyone give me some advices or explains about this?

If I want to continue further operations that are supposed to follow on a successful rollback of the main transaction, like notification messages or emails what should I do in this case?

                    @Override
                    public void afterCompletion(int status) {
                        if (status == TransactionSynchronization.STATUS_ROLLED_BACK) {
                            logger.trace("Rolled back...");
                        }
                    }

Can I ask why you are using this interface?

This is used for callbacks by the PlatformTransactionManager which is in charge of managing the transaction lifecycle.

The "normal" use of Spring Transactions is to utilise @Transactional annotations, aop declarations in xml or TransactionTemplate / PlatformTransactionManager programatically to set the transaction scope, behaviour and visibility, as described in the docs - here .

To manage a transaction behaviour for rollbacks etc you just tell spring what to do in the event of an Exception

public class Foo { 

   @Autowired public Service someService;

    @Transactional(propagation = Propagation.REQUIRES_NEW,
                   noRollbackFor = {IOException.class})
    public boolean bar(SomeObject someObject) throws IOException {
         someService.doComplicatedThing(someObject.getValue());
    }
}

This tells the PlatformTransactionManager to start a new TX when hitting the foo() method, commit on successful return or an IOException, and rollback if there is some other type of exception. This is the genius of it - you dont need to worry about littering your code with getTransaction().isActive() and complicated checks for managing the isolation.

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