Overview
In Spring @Transactional annotation can be used to indicate method should be run in transaction.
When @Transactional is placed on method, this method will be run with transaction. And if it’s placed on a class, all methods of this class will run within transaction.
In MVC style application, we usually wrap business logic into a separate service class annotated with @Service and @Transactional , so every method in this class will run within transaction. But how to disable transaction management for a specific single method in class which is annotated with @Transactional ?
Solution
Add following code before the method which you want to disable transaction management for.
1 |
@Transactional(propagation = Propagation.NEVER) |
Above code will tell Spring PlatformTransactionManager that transaction is not supported for this method, and transaction manager won’t create a new transaction if no transaction is existed.
And if a current transaction existed, exception will be thrown (An IllegalTransactionStateException with message “Existing transaction found for transaction marked with propagation ‘never'”).