Category : Spring Boot | Sub Category : Spring Boot | By Prasad Bonam Last updated: 2023-07-17 11:27:54 Viewed : 62
In Spring Boot, you can roll back multiple transactions within the same method by using the TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
method. Here is an example of how you can achieve this:
java@Service
public class ExampleService {
@Autowired
private PlatformTransactionManager transactionManager;
public void performTwoTransactions() {
TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);
try {
// Perform transaction 1
// ...
// Perform transaction 2
// ...
transactionManager.commit(transactionStatus);
} catch (Exception e) {
transactionManager.rollback(transactionStatus);
}
}
}
In this example, the ExampleService
class has a method called performTwoTransactions()
. Inside the method, you explicitly manage the transactions using the PlatformTransactionManager
.
First, you obtain a TransactionStatus
object by calling transactionManager.getTransaction(transactionDefinition)
, where transactionDefinition
represents the desired transaction settings.
Inside the try
block, you perform the operations for transaction 1 and transaction 2. If an exception occurs, the catch
block is executed, and transactionManager.rollback(transactionStatus)
is called to roll back both transactions.
If no exception occurs, the transactionManager.commit(transactionStatus)
is called to commit the transactions.
By explicitly managing the transactions using the PlatformTransactionManager
, you have control over the rollback behavior and can handle multiple transactions within the same method.