spring-batchitemwritercompositeitemwriter

How do I get inserted key in ItemWriter to use it in another query Spring Batch


I am using Spring Batch, and I will do an Insert in ItemWriter and need to do an update in another table with the key inserted. How do I get the key to use it in the updateTableB ? Thank you in advance.

@Bean
public CompositeItemWriter<TableA> distributionCompositeItemWriter() {
       CompositeItemWriter<TableA> compositeItemWriter = new CompositeItemWriter<>();
       compositeItemWriter.setDelegates(Arrays.asList(processTableA(), updateTableB()));
return compositeItemWriter;
}

@Bean
public ItemWriter<TableA> processTableA() {
    return new JdbcBatchItemWriterBuilder<TableA>()
        .dataSource(dataSource)
            .sql("insert into tableA (id, name) values (tableA_id_seq.nextval, :name)")
            .beanMapped()
            .build();
}

@Bean
public ItemWriter<TableA> updateTableB() {
    return new JdbcBatchItemWriterBuilder<TableA>()
        .dataSource(dataSource)
            .sql("update tableB set tableB_key = :tableA_key where id = :another_field)")
            .beanMapped()
            .build();
}

Solution

  • You could add the id attribute to the TableA class and use an ItemProcessor to populate it (eg. select tableA_id_seq.nextval from dual), then modify the processTableA ItemWriter to use the pre-populated id value (eg. insert into tableA (id, name) values (:id, :name). Then you also have the id available in the updateTableB ItemWriter.