有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSpringBatch:即使捕获到异常,为什么事务仍在回滚

我使用的是Spring批处理,我的步骤配置如下:

 @Bean
  public Step testStep(
      JdbcCursorItemReader<TestStep> testStageDataReader,
      TestStepProcessor testStepProcessor,
      CompositeItemWriter<Writer> testWriter,
      PlatformTransactionManager transactionManager,
      JobRepository jobRepository) {
    return stepBuilderFactory
        .get("TESTING")
        .<>chunk(100)
        .reader(testStageDataReader)
        .processor(testStepProcessor)
        .writer(testWriter)
        .transactionManager(transactionManager)
        .repository(jobRepository)
        .build();
  }

在我的作者中:

 void write(List<? extends TestEntity> items) {

    try {
      testRepository.saveAll(items);
    } catch (Exception exp) {
      log.error("Exception while writing the batch", Exp);
      //If there is an exception try individual items and skip filed ones
      items.forEach(eachTask -> {
      try {
        testRepository.save(eachTask);
      } catch (Exception exp) {
        logException(exp, eachTask.getId());
      }
    });
    }

对于代码,我希望如果批处理出现问题,那么我将尝试单个项目并跳过失败的项目

然而,这并没有发生。事务似乎已丢失且未恢复


共 (1) 个答案

  1. # 1 楼答案

    With the code, I expected that if something goes wrong with the batch then I will try individual items and skip the failed ones.

    这种期望是不正确的。当从项目编写器引发可跳过的异常时,将触发区块扫描。从您的配置来看,情况似乎并非如此:您没有配置任何可跳过的异常,并且您的编写器也没有抛出异常。步骤定义应类似于:

    return stepBuilderFactory
        .get("TESTING")
        // other properties
        .skip(MySkippableException.class)
        .skipLimit(10)
        .build()
    

    你的作者应该在某个时候抛出MySkippableException