Video in progress

Middle 🌱 Spring

How do you see in the logs when @Transactional opens a transaction and when it commits or rolls back?

You turn on DEBUG for the transaction manager in use (for example JpaTransactionManager) and TRACE for org.springframework.transaction.interceptor. In the log you see the lines "Creating new transaction", "Participating in existing transaction", "Committing" or "Rolling back" in sequence.

📖 Answer

For the question "is the transaction even working?", the fastest answer is the log.

logging:
  level:
    org.springframework.orm.jpa.JpaTransactionManager: debug
    org.springframework.transaction.interceptor: trace
    org.hibernate.SQL: debug

You get a sequence roughly like this:

Creating new transaction with name [uz.shop.OrderService.place]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
Getting transaction for [uz.shop.OrderService.place]
insert into orders ...
Participating in existing transaction
Completing transaction for [uz.shop.OrderService.place]
Committing JPA transaction on EntityManager [...]

From the log you can usually find:

  • the method never enters a transaction: there's no "Getting transaction" line. So it's self-invocation, a private method, or the bean isn't proxied;
  • every repository call opens its own transaction: the service has no @Transactional;
  • where REQUIRES_NEW suspends the outer transaction ("Suspending current transaction");
  • which transaction the SQL statements ran inside.

The manager's logger name is the same as its class, so if you use DataSourceTransactionManager, you turn on that one's package. Don't leave these levels on permanently in production: the log volume is huge. If you need it, turn it on for a few minutes through Actuator's /loggers and then switch it back.