Search code examples
javaspringtransactionsspring-batch

Spring Batch Transactions in StepExecutionListener


I have a spring batch job that reads data from a web service, does some enriching in a processor and then saves to DB. If someone runs the same job twice for same set of param I want to delete the old data in db and then re-write as part of this job.

I have written the delete logic in StepExecutionListener Before Step Method.

How can I make my step transactional so that if there is an error in the job the delete operation is rolledback?

this.stepBuilderFactory.get("xStep")
.<Item,Item>chunk(1000)
.reader(xReader)
.processor(xProcessor)
.writer(xWriter)
.listener(xStepExecutionListenerForDelete)
.build()

Solution

  • How can I make my step transactional so that if there is an error in the job the delete operation is rolledback?

    You can write the delete logic as part of the item writer which is called inside the transaction driven by Spring Batch. If the transaction is rolled back for any reason, your delete operation will be rolled back. Note that an item writer is not only used for inserting data, but can be used to update data and delete it as well (MongoItemWriter#setDelete is an example).