【问题标题】:@Transactional Not working with multiple repository calls@Transactional 不适用于多个存储库调用
【发布时间】:2020-11-07 07:50:28
【问题描述】:

我有一个看起来像这样的代码 sn-p

使用@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
    }
}

调用方法的类

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 类中添加了@EnableTransactionManagement。但是如果 repo3 出现异常,repo1 和 repo2 中的数据库操作不会回滚。 每个存储库都使用 Spring JDBCTemplate 来查询数据库。

配置类

@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);
    }
}

【问题讨论】:

  • 这些存储库是连接到不同的数据库还是同一个数据库?您可以添加您的datasource 配置和事务管理器配置吗?
  • 这些都连接到同一个datasource。我在@Configuration 文件中为datasourcetransactionManager 创建了bean。添加配置
  • 显示你正在调用method的类。
  • @chrylis-cautiouslyoptimistic- 我已经相应地编辑了问题陈述。请看一看。
  • (旁注:@Inject@Bean 方法上毫无意义。Spring 已经明白它需要在方法参数中提供 bean。)

标签: java spring-boot transactions


【解决方案1】:

使用 TransactionTemplate 并将我的 repo 调用包含在模板中是可行的。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-11
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多