Niraj Sonawane
Niraj Sonawane

Reputation: 11115

Conditionally send data to multiple writers in spring batch

I have some logic in my processor And based on that I need to decide if I need to write items in TableA (WriterA) or TableB(writer)

e.g Item has filed type and type can have value as A or B and based on value in type filed I need to decide in which table I need to write the data.

Upvotes: 0

Views: 2157

Answers (1)

Niraj Sonawane
Niraj Sonawane

Reputation: 11115

This can be achieved by using Classifier. Below are the configurations:

Writer - Writer will set the Classifer to decide which writer we need to use. Based on classfiter output writer will be decided.

@Bean
public ItemWriter<Pojo> itemWriter() {
    BackToBackPatternClassifier classifier = new BackToBackPatternClassifier();
    classifier.setRouterDelegate(new MyClassifier());
    classifier.setMatcherMap(new HashMap<String, ItemWriter<? extends Pojo>>() {
        {
            put("A", WriterA);
            put("B", WriterB);

        }
    });
    ClassifierCompositeItemWriter<Pojo> writer = new ClassifierCompositeItemWriter<Pojo>();
    writer.setClassifier(classifier);
    return writer;      
}

Classifier

public class MyClassifier {

    @Classifier
    public String classify(Pojo Pojo) {
        return Pojo.getType();
    }
}

Upvotes: 1

Related Questions