首页 > 解决方案 > Spring-boot:如果Service中的方法是@Transactional,并且该方法调用其他方法,它们也是事务性的吗?

问题描述

假设我的@Service 中有这个方法,它是事务性的。如果我在该方法中调用另一个方法,那么另一个方法中的数据库操作是否也作为同一事务的一部分进行事务处理?

@Transactional
public ResponseEntity<List<String>> saveListOfValidationSteps(List<ValidationStep> steps, String controlId, String aNumber){

 deleteOldSteps();
 //calls to repo to add new columns

}

private void deleteOldSteps(){
/calls to repo to delete old columns
}

标签: hibernatespring-bootspring-data-jpa

解决方案


是的,deleteOldSteps() 中的代码将加入当前事务(由 开始saveListOfValidationSteps)。如果你正在使用LocalContainerEntityManagerFactory,那么 spring 将自己管理事务并将entityManager实例附加到ThreadLocal,因此当deleteOldSteps() 内部的代码执行时,sp​​ring首先检查是否EntityManager存在,ThreadLocal如果已经存在则重用(以加入现有的持久性上下文)。

因此,当saveListOfValidationSteps() 从外部调用时,spring 将启动新事务,当deleteOldSteps从本地调用时,它将加入现有事务(由于ThrealLocal数据)。

注意:但是 ifdeleteOldSteps没有用 注释@Transactional,并且 ifdeleteOldSteps不会启动新事务,因为本地调用不会被 spring 方面捕获。


推荐阅读