Batch Tasklet to read from database with select query

2.7k views Asked by At

How can I create a tasklet class to make a custom select query from DB and pass the data to the next tasklet? I have to use tasklet (no jdbcReader or any reader)

Code Sample:

public class Taskletreader implements Tasklet, StepExecutionListener{
    
    private final Logger logger = LoggerFactory.getLogger(Taskletreader.class);
    @Autowired
    private DataSource dataSource;
    private List<FichierEclate> FichierEclates;
private String query="select * from FicherEclate where .......some conditions...."

    @Override
    public void beforeStep(StepExecution stepExecution) {
        FichierEclates = new ArrayList<FichierEclate>();
       logger.debug("Reader initialized.");
    }

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        new JdbcTemplate(dataSource)
        .execute(query);
        return RepeatStatus.FINISHED;
    }

     @Override
        public ExitStatus afterStep(StepExecution stepExecution) {
          //  fu.closeReader();
            stepExecution
              .getJobExecution()
              .getExecutionContext()
              .put("FichierEclates", this.FichierEclates);
            logger.debug("Reader ended.");
            return ExitStatus.COMPLETED;
        }

}

Can't understand where is the result of the select and how to pass it to next tasklet for processing ?

1

There are 1 answers

0
Mahmoud Ben Hassine On BEST ANSWER

Can't understand where is the result of the select

If you want to consume the result of the query, you can use the query method on JdbcTemplate:

List<FichierEclate> fichierEclates = jdbcTemplate.query(query, new BeanPropertyRowMapper<>(FichierEclate.class));

This method accepts a RowMapper that maps each row from the database to an instance of your domain object. The sample uses BeanPropertyRowMapper, but you can provide a custom mapper if needed.

how to pass it to next tasklet for processing ?

You can use the execution context for that as you did. However, you should not be passing the entire items list. The execution context is persisted and it is not recommended to pass a lot of data between steps like this. A list of item IDs could be fine, but the list of entire items objects is not a good idea. Please refer to the Passing Data to Future Steps section of the reference documentation for more details.

That said, I really recommend using a chunk-oriented tasklet for that. I know you said I have to use tasklet (no jdbcReader or any reader), but I don't understand this constraint.