Aure77
Aure77

Reputation: 3209

Spring Batch writer depending on processed item

How to change or choose a specific writer depending on item property ? For example, I need to write to different SQL table (Table A and B).

if(item.myBoolean==true) { Write to A and B } else { Write only on A }

How to choose wich JdbcBatchItemWriter to use ? (Actually I use a CompositeItemWriter to write into my 2 JdbcBatchItemWriter) Do I need to create a custom ItemWriter "decider" or there is another best solution (from processor) ?

Upvotes: 2

Views: 2217

Answers (2)

Niraj Sonawane
Niraj Sonawane

Reputation: 11115

 @Bean
    public ItemWriter<Person> itemWriter(DataSource dataSource) {
        BackToBackPatternClassifier classifier = new BackToBackPatternClassifier();
        classifier.setRouterDelegate(new AggGroupClassifier());
        classifier.setMatcherMap(new HashMap<String, ItemWriter<? extends Person>>() {
            {
                put("A", writerA(dataSource));
                put("B", writerB(dataSource));
                put("C", writerC(dataSource));

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


public class AggGroupClassifier {

    @Classifier
    public String classify(Person person) {
        return person.getAgeGroup();

    }
}

Upvotes: 0

Aure77
Aure77

Reputation: 3209

I found the solution by using ClassifierCompositeItemWriter

ClassifierCompositeItemWriter<Subscription> classifierCompositeItemWriter = new ClassifierCompositeItemWriter<Subscription>();      
classifierCompositeItemWriter.setClassifier(new Classifier<Subscription, ItemWriter<? super Subscription>>() {          
    @Override
    public ItemWriter<? super Subscription> classify(Subscription classifiable) {
        ItemWriter<? super Subscription> itemWriter = null;
        if(classifiable.isComplex()) { // condition
            itemWriter = compositeItemWriter; // I use compositeItemWriter to write on A and B
        } else {
            itemWriter = subscriptionJdbcWriter; // I use single JdbcBatchItemWriter to write only on A
        }
        log.info("Subscription would be classified with " + itemWriter.getClass().getSimpleName());
        return itemWriter;
    }
});

Upvotes: 3

Related Questions