Search code examples
javaspringtransactions

Creating a post commit when using transaction in Spring


Due to certain reasons, I have manually performed transaction commit and roll back using Spring PlatformTransactionManager. I want to set up a hook so that a post commit action takes place after transaction has been committed.

By looking at:

void commit(TransactionStatus status) throws TransactionException;

I can't see how I can determine a transaction was successful other than assuming it so if no exception are thrown.

And I could use AOP as one option, but what about programmatically doing it, maybe using callback method?


Solution

  • You could get exactly what you want by a simpler way, with TransactionSynchronizationManager and TransactionSynchronization

    With TransactionSynchronizationManager, you have static methods to get information about current transaction, and you can register a TransactionSynchronization wich allows you to automatically do a post-commit as you call that

    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization(){
               void afterCommit(){
                    //do what you want to do after commit
               }
    })
    

    Be aware that the TransactionSynchronization is on a per-thread basis (which is often not a problem for a basic web request).