How to set up a Spring Batch single reader with multiple itemwriters?

Viewed 328

I've a situation where I've to perform DB operations to 2 different databases as shown below.

stepBuilderFactory.get("some text")
                  .<POJO,POJO>chunk(200) 
                  .reader(dataReader)
                  .writer(writeToDB1)
                  .writer(writeToDB2) 
                  .faultTolerant()
                  .skipLimit(10) 
                  .skip(DataAccessException.class)
                  .build();

Only the second writer is getting executed, ignoring the first writer. Can this can be achieved using Spring Batch 3.x & Spring Boot 1.5.x?

1 Answers

CompositeItemWriter is what you need. It allows you to compose delegate writers to write items to multiple destinations.

When your delegate writers are ItemStreams (which is apparently the case for you), you need to register them as streams in the step so that their callback methods from the ItemStream interface are properly called at the necessary points of the step lifecycle (or in short, so that their ItemStream contract is correctly honored). You can find more details on this in the Registering ItemStream with a Step section of the reference documentation.

Hope this helps.

Related