Search code examples
springspring-batchbatch-processing

Spring Batch - Updating different tables based on conditions


Spring batch

Not sure how to implement this but requirements are let's say we have condition A/B:

  • If it's A - I have to update/delete/insert in tables D/E/F

  • If it's B - I have to update/delete/insert in tables G/H/I

The transaction should be done in a single transaction, meaning that under condition A, I have to finish updating all 3 tables - D, E, F. In case any table fails, this transaction shouldn't be partially done.

Was thinking of classifier + composite item writer but not sure if it's a single transaction.


Solution

  • Using a classifier makes sense only when items should/could be classified. So if your condition depends on item types (ie classes), then using a classifier + composite writer is the way to go. If you use a composite writer, the transaction will be around the composite writer, with all-or-nothing semantics for your insert/update/delete statements. You can find a complete example here: How does Spring Batch CompositeItemWriter manage transaction for delegate writers?

    If your condition does not depend on item types (like for example a job parameter or a system property), then you can create a custom writer for that (This writer could delegate to two composite writers and call the appropriate one based on the condition).