Spring 事务管理 @Transactional 行为

Spring Transaction Management @Transactional behavior

我想知道 Spring @Transactional 如何适用于以下编码方案。对于此示例,我使用 Spring 4 + Hiberante 5 和 Oracle 19C 数据库。

示例 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() {
        // ...
    }
}

示例 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() {
        // ...
    }
}

谢谢

示例 1:当您从 inside 您的服务调用 createPDF 方法时,@Transactional(REQUIRES_NEW) 注释将有效地 ignored。不会有新交易开启。

示例 2:当您调用另一项服务时,该服务包装在事务代理中,您将得到一个 new transaction,因为注解得到尊重。

您可能还想阅读这篇文章:Spring Transaction Management: @Transactional In-Depth