【问题标题】:Spring batch - pass values between reader and processorSpring batch - 在读取器和处理器之间传递值
【发布时间】:2017-11-21 12:20:32
【问题描述】:

我有一个要求,我需要从 xls(存在名为 netCreditAmount 的列)中读取值并将值保存在数据库中。要求是从所有行中添加 netCreditAmount 的值,然后在数据库中仅为 xls 中的第一行设置此总和,其余行与其相应的 netCreditAmount 一起插入。 我应该如何继续在 Spring Batch 中实现。普通阅读器、处理器和编写器工作正常,但我应该在哪里插入这个实现? 谢谢!

【问题讨论】:

  • 由于需要对读取的数据进行处理,所以应该对Processor类中的对象进行处理和更新。

标签: spring spring-batch


【解决方案1】:

你可以通过添加额外的 tasklet 来解决这个问题。 工作流程可以如下所示

@Bean
    public Job myJob(JobBuilderFactory jobs) throws Exception {
        return jobs.get("myJob")
                .start(step1LoadAllData())  // This step will load all data in database excpet first row in xls
                .next(updateNetCreditAmountStep()) //// This step will be a tasklet. and will update total sum in first row. You can use database sql for sum for this 
                .build();           

    }

Tasklet 如下所示

@Component
public class updateNetCreditAmountTasklet implements Tasklet {  

    @Override
    public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext)
            throws Exception {
            Double sum = jdbctemplate.queryForObject("select sum(netCreditAmount) from XYZ", Double.class);
         // nouw update this some in database for first row 
        return null;
    }

}

【讨论】:

    【解决方案2】:

    那么问题是什么? 您需要设置批处理作业步骤以使用 reader-processor-writer。

    阅读器有接口:

    public interface ItemReader<T> {    
      T read();
    }
    

    处理器:

    public interface ItemProcessor<I, O> {
      O process(I item);
    }
    

    所以你需要有读者提供的相同类型 - T;并将其传递给处理器 - I

    stepBuilderFactory.get("myCoolStep")
                .<I, O>chunk(1)
                .reader(myReader)
                .processor(myProcessor)
                .writer(myWriter)
                .build();
    

    【讨论】:

      猜你喜欢
      • 2018-06-23
      • 2015-12-20
      • 1970-01-01
      • 2018-02-06
      • 2018-03-23
      • 2013-09-30
      • 2012-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多