You can obtain the present transaction using Spring PlatformTransactionManager by calling the static method TransactionAspectSupport.currentTransactionStatus() which will return the present transaction status.
The following is an example code:
@Service
public class TransactionService {
@Autowired
private PlatformTransactionManager transactionManager;
public void method1() {
// get the present transaction status
TransactionStatus status = TransactionAspectSupport.currentTransactionStatus();
// use the transaction status
boolean isNewTransaction = status.isNewTransaction();
// ...
}
@Transactional
public void method2() {
// get the present transaction status
TransactionStatus status = TransactionAspectSupport.currentTransactionStatus();
// use the transaction status
boolean isNewTransaction = status.isNewTransaction();
// ...
}
}
In this example, we obtain the present transaction status for method1()
and method2()
by calling TransactionAspectSupport.currentTransactionStatus()
within the method. Then we can use the transaction status to check whether it is a new transaction or commit/roll back the transaction, etc.
Asked: 2022-01-08 11:00:00 +0000
Seen: 25 times
Last updated: Oct 31 '22