In the batch job step configuration, I plan to execute 2 queries in the writer, the 1st query is to update records in table A, then the 2nd query is to insert new records in table A again.
So far I think CompositeItemWriter can achieve my goal above, i.e., I need to create 2 JdbcBatchItemWriters, one is for update, and the other one is for insert.
My first question is if CompositeItemWriter is a fit for the requirement above?
If yes, that lead to the second question about transaction. For example, if the first update is successful, and the second insert fails. Will the 1st update transaction be rolled back automatically? Otherwise, how to manually pull both updates in the same transaction?
Thanks in advance!
Yes,
CompositeItemWriter
is the way to go.Excellent question! Yes, if the update succeeds in the first writer and then the insert fails in the second writer, all statements will be rolled back automatically. What you need to know is that the transaction is around the execution of the chunk oriented tasklet step (and so around the
write
method of the composite item writer). Hence, the execution of all sql statements within this method (executed in delegate writers) will be atomic.To illustrate this use case, I wrote the following test:
people
with two columnsid
andname
with only one record inside it:1,'foo'
1,'foo'
,2,'bar'
) and tries to updatefoo
tofoo!!
and then inserts2,'bar'
in the table. This is done with aCompositeItemWriter
with two item writers:UpdateItemWriter
andInsertItemWriter
UpdateItemWriter
succeeds butInsertItemWriter
fails (by throwing an exception)foo
is not updated tofoo!!
andbar
is not inserted in the table (Both sql statements are rolled back due to the exception in theInsertItemWriter
)Here is the code (it is self-contained so you can try it and see how things work, it uses an embedded hsqldb database which should be in your classpath):
My example uses custom item writers but this should work with two
JdbcBatchItemWriter
s as well.I hope this helps!