user2611221
user2611221

Reputation: 99

spring boot spring batch: how to set query dynamically to ItemReader

I am new to Spring. I have a use case where I need to execute same multiple sql queries and return same POJO for every query. I would like to write one Item reader and change the query in each step. Is there a way to do this?

Upvotes: 0

Views: 2936

Answers (1)

Niraj Sonawane
Niraj Sonawane

Reputation: 11055

You can use spring batch late binding by adding @StepScope in your reader

Sample code

@StepScope
@Bean
public ItemReader<Pojo> myReader() {
    JdbcCursorItemReader<Pojo> reader = new JdbcCursorItemReader<>();
    reader.setDataSource(basicDataSource);
    //You can inject sql as per you need 
    //Some expamles 
    //using #{jobParameters['']}
    //using {jobExecutionContext['input.file.name']}" 
    //using #{stepExecutionContext['input.file.name']}"
    reader.setSql("Your-SQL");      
    reader.setRowMapper(new MyMapper());
    return reader;
}

check section 5.4 https://docs.spring.io/spring-batch/reference/html/configureStep.html

Upvotes: 1

Related Questions