Sobes.tech
Junior — Middle

How to initiate a new transaction inside a method annotated as @Service?

sobes.tech AI

Answer from AI

In Spring, to initiate a new transaction within a method annotated as @Service, the @Transactional annotation with the parameter propagation = Propagation.REQUIRES_NEW is used. This means that when such a method is called, a new transaction will be created, even if there is already an active transaction.

Example:

@Service
public class MyService {

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

If the method is called from another method that is already within a transaction, the current transaction will be suspended, and a new one will be started. This is useful when you need to perform an independent operation with a separate transaction.

How to initiate a new transaction inside a method… - sobes.tech