Sobes.tech
Senior

How can two transactions be created in one class (bypassing self-invocation limitation)?

sobes.tech AI

Answer from AI

In Java, when using Spring and the @Transactional annotation, self-invocation issues occur because calling a transactional method within the same class does not go through the proxy, and the annotation does not take effect.

To create two separate transactions within a single class and bypass this limitation, you can:

  1. Extract methods with different transactions into a separate service and call them through the injected bean (via proxy).

  2. Use ApplicationContext to obtain the proxy of the current bean and call methods through it:

@Service
public class MyService {

    @Autowired
    private ApplicationContext context;

    @Transactional(propagation = Propagation.REQUIRED)
    public void method1() {
        // ...
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void method2() {
        // ...
    }

    public void caller() {
        context.getBean(MyService.class).method1();
        context.getBean(MyService.class).method2();
    }
}
  1. Use AspectJ instead of proxies, so self-invocation works correctly.

Thus, the key is to call transactional methods through proxies, not directly within the same class.