I am writing a Spring Batch job to:
- Read some records from a database table
- Write them to a file
- Update the same records on the same database table
My solution so far involves:
- A JdbcCursorItemReader which reads from the database
- A CompositeItemWriter which, in turn, delegates to
- An ItemWriter to write to a file
- A JdbcBatchItemWriter to update the processed records on the database
How can I make sure that the whole step runs in a single transaction? I would be able to commit the database UPDATE only if the step is successful.
Here is the relevant Java-based configuration code:
@Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.<Person, Person>chunk(...)
.reader(...)
.processor(...)
.writer(compositeWriter())
.build();
}
@Bean
public CompositeItemWriter<Person> compositeWriter() {
return new CompositeItemWriterBuilder<Person>()
.delegates(..., jdbcWriter())
.build();
}
@Bean
public JdbcBatchItemWriter<Person> jdbcWriter(DataSource dataSource) {
return new JdbcBatchItemWriterBuilder<Person>()
.itemSqlParameterSourceProvider(...)
.sql("UPDATE ...")
.dataSource(dataSource)
.build();
}