Search code examples
springspring-boottransactionsspring-batch

Running a Spring Batch step in a single transaction


I am writing a Spring Batch job to:

  1. Read some records from a database table
  2. Write them to a file
  3. Update the same records on the same database table

My solution so far involves:

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();
}

Solution

  • Running the entire step in a single transaction is not the purpose of the chunk-oriented processing model in the first place. The reason is obviously related long running transactions when dealing with large volumes of data.

    That said, nothing prevents you from creating a custom step implementation that does the work in a single transaction if this works for you, even though I would not recommend that.