Nikhil Nadkar
Nikhil Nadkar

Reputation: 43

Spring batch can classifer return multiple writers

I am new to Spring batch I have a large master table. This master table gets merged into 5 separate tables My requirement is I need to create a writer which will write to these 5 separate tables. But these writers will be called based on the condition For Eg: If I have a field which is not set in the master table I'll call 2 writers and skip the other 3 .

I used a composite writer with classifier to check for the condition but the classifier only returns 1 writer. Can the classifier return multiple writers or is there any other class which can satisfy my requirement?

Upvotes: 0

Views: 422

Answers (1)

Ken Chan
Ken Chan

Reputation: 90517

You can create a custom ItemWriter which combine several ItemWriter for handling a specific case. For example suppose there are two cases which require different ItemWriter. Case1 requires to write to table1 and table2 :

@Component
public class Case1ItemWriter implements ItemWriter<Foo> {

    @Autowired
    private JdbcBatchItemWriter writer1;  //write to table1

    @Autowired
    private JdbcBatchItemWriter writer2;  //write to table2

    @Override
    public void write(List<? extends T> items) throws Exception{
        writer1.write(items);
        wrtire2.write(items)
    }
}

And case2 requires to write to table3 and table4 :

@Component
public class Case2ItemWriter implements ItemWriter<Foo> {

    @Autowired
    private JdbcBatchItemWriter writer3;  //write to table3

    @Autowired
    private JdbcBatchItemWriter writer4;  //write to table4

    @Override
    public void write(List<? extends T> items) throws Exception{
        writer3.write(items);
        wrtire4.write(items)
    }
}

Then implement a Classifier to determine different cases to return their own ItemWriter:

@Component
public class MyClassifier implements Classifier<Foo ,ItemWriter<Foo>> {

    @Autowired
    private Case1ItemWriter case1ItemWriter;

    @Autowired
    private Case2ItemWriter case2ItemWriter;  

    @Override
    public ItemWriter<Foo> classify(Foo foo){

      if(foo.isBlabBlaBla()){
        return case1ItemWriter;
      }else{
        ......
        return case2ItemWriter;
      }
    }
}

And configure this Classifier to the ClassifierCompositeItemWriter .

Upvotes: 1

Related Questions