@Transactional 不适用于多个存储库调用

@Transactional Not working with multiple repository calls

我有一个看起来像这样的代码片段

使用@Transactional 方法的服务

public class XService {
    private Repo1 repo1;
    private Repo2 repo2;
    private Repo3 repo3;

    XService(Repo1 repo1, Repo2 repo2, Repo3 repo3) {
        this.repo1 = repo1;
        this.repo2 = repo2;
        this.repo3 = repo3;
    }

    @Transactional(rollbackFor = Exception.class)
    public SomeObject method(Arg1 arg1, Arg2 arg2) {
        repo1.method1();
        repo2.method2();
        repo3.method3(); // probability of exception here, in which case rollback is needed
    }
}

Class 从哪里调用方法

public class YService {
    private XService xService;
  
    public YService(XService xService) {
        this.xService = xService;
    }
  
    public SomeObject method(Arg1 arg1, Arg2 arg2) {
        xService.method(arg1, arg2);
    }
}

我还在 SpringBootApplication class 上添加了 @EnableTransactionManagement。但是在 repo3 异常的情况下,repo1 和 repo2 的数据库操作不会回滚。 每个存储库都使用 Spring JDBCTemplate 来查询数据库。

配置class

@Configuration
public class ConfigurationClass {

    @Bean
    @Inject
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    @Inject
    public DataSource dataSource() {
        // setting config properties here
        return new HikariDataSource(config);
    }

    @Bean
    @Inject
    public Repo1 repo1(JDBCTemplate template) {
      return new Repo1(template);
    }

    @Bean
    @Inject
    public Repo2 repo2(JDBCTemplate template) {
      return new Repo2(template);
    }

    @Bean
    @Inject
    public Repo3 repo3(JDBCTemplate template) {
      return new Repo3(template);
    }

    @Bean
    @Inject
    public XService XService(Repo1 repo1, Repo2 repo2, Repo3 repo3) {
      return new XService(repo1, repo2, repo3);
    }

    @Bean
    @Inject
    public YService YService(XService xService) {
      return new YService(xService);
    }
}

使用 TransactionTemplate 并将我的回购调用包含在模板中有效。

transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) throws TransactionException {
          repo1.method1();
          repo2.method2();
          repo3.method3();
        }
      });

我不知道这个方法起作用的原因。如果有人能帮助理解这背后的原因,那就太好了。