我有以下代码

@Bean
public JdbcBatchItemWriter<QuotationDto> writer1() {
    return new JdbcBatchItemWriterBuilder<QuotationDto>()
            .itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
            .sql("INSERT INTO ...")
            .dataSource(dataSource)
            .build();
}

@Bean
public JdbcBatchItemWriter<QuotationDto> writer2() {
    return new JdbcBatchItemWriterBuilder<QuotationDto>()
            .itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
            .sql("INSERT INTO ...")
            .dataSource(dataSource)
            .build();
}

@Bean
public CompositeItemWriter<QuotationDto> compositeItemWriter() {
    CompositeItemWriter writer = new CompositeItemWriter();
    writer.setDelegates(Arrays.asList(writer1(), writer2()));
    return writer;
}

@Bean
public Step step1() {
    return stepBuilderFactory.get("step1")
            .<QuotationDto, QuotationDto>chunk(5)
            .reader(reader())
            .processor(processor())
            .writer(compositeItemWriter())
            .stream(writer1())
            .stream(writer2())
            .build();
}


在将writer1设置为流时出现IntelliJ错误,因为id没有实现ItemStream。

我究竟做错了什么?有人有解决方案吗?我找不到太多有关基于Java的复合编写器配置的信息。

最佳答案

JdbcBatchItemWriter没有实现ItemStream,因此不能在面向块的步骤中用作流。

如果要组成两个JDBC项目编写器,则可以创建一个委托给JdbcTemplate的自定义项目编写器。这是一个简单的示例:

class MyItemWriter implements ItemWriter<QuotationDto> {

    private JdbcTemplate jdbcTemplate;

    public MyItemWriter(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public void write(List<? extends QuotationDto> items) throws Exception {
        for (QuotationDto dto : items) {
            // use jdbcTemplate to batch insert items.
            // can do multiple inserts here, they will be part of
            // the same transaction driven by Spring Batch
        }
    }
}

09-05 10:54