Search code examples
spring-batchspring-integration

Read one record/item and write multiple records/items using spring batch


I did some searching but couldn't find any sample/example.

I've a requirement where geo coordinates from one table (input) are read, processed to generate POI's associated to coordinate. So one geo coordinate will result in one or more POI's that needs to be inserted into another table (output).

I'm currently using a JdbcCursorItemReader and JdbcBatchItemWriter to read one item/record and write one item/record. There is also an ItemProcessor that generates the POI's for a give geo coordinate.

Does a custom JdbcBatchItemWriter help me achieve this?

Any ideas? TIA.


Solution

  • if you just want to spread the items to different writers (read duplicate output) you can use the existing CompositeItemWriter

    but i'm not sure if your processor will produce different item types or if you want to spread the content of one complex item type to multiple writers, for those cases you can use a slightly changed version for a multiline-record-writer question

    public class MultiOutputItemWriter implements ItemWriter<Object> {
    
    private JdbcBatchItemWriter<ClassFoo> delegateFoo;
    private JdbcBatchItemWriter<ClassBar> delegateBar;
    
    public void write(List<? extends Object> items) throws Exception {
           // if you have different types of items
           // check Object Class
           // add to new List<Classfoo>
           // call delegate e.g. delegateFoo.write(List with ClassFoo);
           //
           // or if you have complex objects
           // same procedure as above, but with
           // add to new List<Classfoo> with item.getClassFoo
     }
    }
    

    if you use FlatFileItemWriter, do not forget to register the delegates as ItemStreams (so spring batch will open/close them for you)