Sobes.tech
Junior — Middle

How is it recommended to run a method inside a new transaction in an application?

sobes.tech AI

Answer from AI

To invoke a method within a new transaction in a Java application, especially when using the Spring Framework, it is recommended to use the @Transactional annotation with the parameter propagation = Propagation.REQUIRES_NEW.

This ensures that the method will be executed in a separate transaction, regardless of any existing one. If there is an active transaction, it will be suspended, and a new one will be started for the method.

Example:

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void myMethod() {
    // code executed in a new transaction
}

It is important that such a method is called through a Spring proxy (for example, from another bean), otherwise the annotation will not work.