Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way of detecting if a Spring DB transaction is active than using TransactionSynchronizationManager.isActualTransactionActive()?

I have some legacy code that I am now trying to re-use under Spring. This code is deeply nested in other code so it's not practical to redesign and is called in many situations, only some of which are through Spring. What I'd like to do is to use the Spring transaction if one has been started; otherwise, continue to use the existing (legacy) db connection mechanism. Our first thought was to make our legacy class a bean and use an injected TransactionPlatformManager, but that does not seem to have any methods germane to our situation. Some research showed that Spring has a class called TransactionSynchronizationManager which has a static method isActualTransactionActive(). My testing indicates this method is a reliable way of detecting if a Spring transaction is active:

  • When called via Spring service without the @Transactional annotation, it returns false
  • When called via Spring service with @Transactional, it returns true
  • In my legacy method called the existing way, it returns false

My question: Is there a better way of detecting if a transaction is active?

like image 713
fool4jesus Avatar asked Aug 16 '11 18:08

fool4jesus


People also ask

Why applying Spring @transactional annotation on the concrete class or its methods is recommended rather than on interface?

Spring's recommendation is that you annotate the concrete implementations instead of an interface. It's not incorrect to use the annotation on an interface, it's just possible to misuse that feature and inadvertently bypass your @Transaction declaration.

How would you enable transactions in Spring and what are their benefits?

The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits: Consistent programming model across different transaction APIs such as Java Transaction API (JTA), JDBC, Hibernate, Java Persistence API (JPA), and Java Data Objects (JDO).


1 Answers

No better way than the TransactionSynchronizationManager.isActualTransactionActive(). It is the utility method used by spring to handle the transactions. Although it is not advisable to use it within your code, for some specific cases you should - that's why it's public.

Another way might be to use the entity manager / session / connection and check there if there's an existing transaction, but I'd prefer the synchronization manager.

like image 53
Bozho Avatar answered Sep 29 '22 12:09

Bozho