Uwe Allner
Uwe Allner

Reputation: 3467

How can I determine whether I am in a transaction in Spring?

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.

Upvotes: 19

Views: 28373

Answers (2)

Mykola Yashchenko
Mykola Yashchenko

Reputation: 5371

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

Upvotes: 40

Pio Ko
Pio Ko

Reputation: 41

You can use

org.springframework.transaction.support.TransactionSynchronizationManager#isActualTransactionActive

Upvotes: 4

Related Questions