javaspringhibernatetransactionsspring-transactions

Spring Transaction Management @Transactional behavior


I wanted to know how the Spring @Transactional will work for the following Coding scenarios. I am using Spring 4 + Hiberante 5 with Oracle 19C database for this example.

Example 1:

@Service
public class UserService {
    @Transactional(readOnly = true)
    public void invoice() {
        createPdf();
        // send invoice as email, etc.
    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void createPdf() {
        // ...
    }
}

Example 2:

@Service
public class UserService {
    @Autowired
    private InvoiceService invoiceService;
    @Transactional(readOnly = true)
    public void invoice() {
        invoiceService.createPdf();
        // send invoice as email, etc.
    }
}
@Service
public class InvoiceService {
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void createPdf() {
        // ...
    }
}

Thanks


Solution

  • Example 1: As you are calling the createPDF method from inside your Service, the @Transactional(REQUIRES_NEW) annotation will effectively be ignored. There will be no new transaction opened.

    Example 2: As your are calling another service, which is wrapped in a transactional proxy, you will get a new transaction, as the annotation is respected.