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

  • Rolling back when some inserts throw DuplicateKeyException

    Hi,

    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!

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

  • #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?

    Comment

    Working...
    X