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:
@Transactional
annotation, it returns false@Transactional
, it returns trueMy question: Is there a better way of detecting if a transaction is active?
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With