13

I have a problem with persistence in a Spring service. A Rest-Controller R receives a request, and calls a service S via a complex way through some layers of code. The service method in S declares a transaction; this should be the first time a transaction should be started. But the service behaves like a transaction already had been started before, and some of my data objects would be part of the session (which they must not). How can I determine if a transaction is already active? I have tried to inject EntityManager and/or JpaTransactionManager; but both seem to be of no help.

How can I check whether I am in a transaction or not?

I want to be sure of that before I go hunting through all these layers searching for possible suspects.

Neil Stockton
  • 10,922
  • 3
  • 30
  • 28
Uwe Allner
  • 3,265
  • 9
  • 37
  • 48
  • Not answering your question directly, but it sounds like you've fallen victim to Open Session In View (OSIV) just like us. It is enabled by default (for historical reasons). Check [another thread in StackOverflow](https://stackoverflow.com/questions/30549489/what-is-this-spring-jpa-open-in-view-true-property-in-spring-boot) for more details. – mmastika Sep 24 '20 at 06:51

2 Answers2

32

You can check if transaction is active using TransactionSynchronizationManager.isActualTransactionActive(). But you should call it before a service method executing.

Also you can get status of current transaction using

TransactionStatus status = TransactionAspectSupport.currentTransactionStatus();

Besides, maybe a good point for you is to enable logging of transactions.

log4j.logger.org.hibernate.transaction=DEBUG
log4j.logger.org.springframework.transaction=DEBUG
informatik01
  • 15,636
  • 10
  • 72
  • 102
Mykola Yashchenko
  • 4,725
  • 3
  • 36
  • 45
  • 4
    What if I get TransactionSynchronizationManager.isActualTransactionActive() = true, but TransactionAspectSupport.currentTransactionStatus() throws: No transaction aspect-managed TransactionStatus in scope? – Andrii Bobrov Apr 25 '20 at 09:33
2

You can use

org.springframework.transaction.support.TransactionSynchronizationManager#isActualTransactionActive
Pio Ko
  • 21
  • 2