Announcement Announcement Module
No announcement yet.
Rolling back when some inserts throw DuplicateKeyException Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Rolling back when some inserts throw DuplicateKeyException


    We're trying to find a way in Spring Batch to roll back the entire chunk when there are DuplicateKeyException(s). So consider the following example:

    4 records total with 2 records causing DuplicateKeyException and 2 records which are valid.
    When this scenario occurs we do not want the 2 valid records to get inserted into the Database.

    Additionally, we would want the offending records to get reported in our log file. Meaning, it would not stop trying to insert remaining records at the first sign of an error.

    Thanks in advance!

            <batch:step id="step1">
                    <batch:chunk reader="reader" processor="processor" writer="writer" commit-interval="4" skip-limit="4">
                            <batch:include class="java.lang.Exception"/>
                            <batch:exclude class="org.springframework.batch.item.file.FlatFileParseException" />
                            <batch:exclude class="java.lang.NumberFormatException" />
                            <batch:exclude class="" />
    <!--                        <batch:exclude class="org.springframework.dao.DuplicateKeyException" />-->
                        <batch:listener ref="readListener" />
                        <batch:listener ref="writeListener" />
                        <batch:listener ref="stepExecutionListener" />
                        <batch:listener ref="skipListener" />
                    <batch:transaction-attributes isolation="DEFAULT"
                <batch:next on="*" to="step2" />

  • #2
    Rollback is the default outcome for an exception in your chunk. You have overridden that in the sample by setting skippable exceptions, so you should see your two bad items skipped, and the rest eventually committed. If you want to stop the job when the exceptions occur and not commit the good records, you just need to make this exception type non-skippable. I feel like I am missing something though - what do you want the outcome of the whole step to be?