Sobes.tech
Junior — Middle

How to count the number of transactional operations when calling one method annotated with @Transactional inside another method within the same transactional scope in Spring?

sobes.tech AI

Answer from AI

In Spring, when calling one method annotated with @Transactional from another method within the same transactional context, the same transaction is actually used if an outer transaction is already active. The internal call does not create a new transaction because Spring proxies do not intercept calls within the same bean.

To count the number of transactional operations (for example, how many times a new transaction starts), you can use:

  • Logging transactions via TransactionSynchronizationManager.
  • Injecting a custom PlatformTransactionManager or using AOP to count transaction starts.

Example using AOP to count transaction starts:

@Aspect
@Component
public class TransactionCounterAspect {
    private AtomicInteger transactionCount = new AtomicInteger(0);

    @Before("execution(@org.springframework.transaction.annotation.Transactional * *(..))")
    public void beforeTransactionalMethod() {
        if (!TransactionSynchronizationManager.isActualTransactionActive()) {
            transactionCount.incrementAndGet();
        }
    }

    public int getTransactionCount() {
        return transactionCount.get();
    }
}

Thus, if the method is called within an already active transaction, the counter will not increase, as a new transaction is not created. If a new transaction is started, the counter will increase. This helps to understand how many transactions actually started during method calls.