Saturday 12 March 2022

Detecting a active transaction in spring application

Sometimes we need to use transactions (@Transactional) in code. We use @Transactional annotation on class and method to generate transactions.

In order to troubleshoot transaction issues, it could be helpful to verify if we have an active transaction in the current method or not.

Spring has provided a class called TransactionSychronizationManager. This class has a static method that allows us to know whether we are in a transaction (active transaction or no transaction), called isActualTransactionActive().

You can call this method and print output in logs. It will be true for active transactions false otherwise.

For example :

logger.error("Transaction is active " + TransactionSynchronizationManager.isActualTransactionActive());