0
votes

I need to create a spring batch wherein i need to fetch data from 2 different tables. This will be the reader part.

The problem is i need to have 2 reader queries. And only one of them will be called based on the condition. But the writer will be same. So tasklet becomes same basically.

Can i have 2 readers inside one single step which will be called according to the condition..??

Something like inside the spring batch xml:

if (condition)
then reader1
else reader2


...
....
......


<reader1 id=".." class="..">

</reader1>

.....
........

<reader2 id=".." class="..">

</reader2>

1
only one of them will be called based on the condition: What is the condition based on? A job parameter? A system property? Something calculated in a previous step? I see no need to have two readers in your case, this is a matter of configuration IMO. - Mahmoud Ben Hassine

1 Answers

1
votes

Have you considered using the conditional control flow patterns Spring Batch offers? I think it could lead to simpler construction and adhere to some of the core patterns spring batch encourages.

You basically program the "condition" that you want a step to be called under. So define two steps, say step1 which has a reader, processor, writer for one object type and step2 which has a reader, processor, writer for the other type. Perhaps the writers are shared between types as well. You then can define control flow like so:

    @Bean
    public Job myJob() {
        JobBuilder jobBuilder = jobs.get("Spring Batch: conditional steps");
     
        return jobBuilder.start(determineRoute())
                             .on("item1").to(flow1())
                             .on("item2").to(flow2()).end()
                         .build();
                 
    }

In the example determineRoute() is a tasklet that returns custom ExitStatus values item1 or item2 & flow1 and flow2 are different flows (or steps) to handle each object.

See here in their docs: https://docs.spring.io/spring-batch/docs/current/reference/html/step.html#conditionalFlow

Edit: you can also do something similar with a JobExecutionDecider https://www.baeldung.com/spring-batch-conditional-flow#2-programmatic-branching-withjobexecutiondecider