Spring: 如何在for循环中重启事务?

Spring: How to restart transaction in a for-loop?

我有一个 Spring 批处理应用程序,它在 write 步骤中循环遍历要插入到 Postgres 数据库中的记录。我们时不时地在循环中得到一个 DuplicateKeyException,但不希望整个工作失败。我们记录该记录并希望继续插入以下记录。

但是在出现异常时,事务变为 "bad" 并且 Postgres 将不再接受任何命令,如 in this excellent post 所述。所以我的问题是,重启交易的最佳方式是什么?同样,我不会重试失败的记录 - 我只想继续循环处理下一条记录。

这是我的工作配置的一部分 xml:

<batch:job id="portHoldingsJob">
    <batch:step id="holdingsStep">
        <tasklet throttle-limit="10">
             <chunk reader="PortHoldingsReader"  processor="PortHoldingsProcessor" writer="PortHoldingsWriter" commit-interval="1" />
        </tasklet>
    </batch:step>
    <batch:listeners>
        <batch:listener ref="JobExecutionListener"/>
    </batch:listeners>
</batch:job>

感谢任何意见!

不确定您是否正在使用 Spring 事务注释来管理事务...如果是这样也许您可以尝试。

   @Transactional(noRollbackFor = DuplicateKeyException.class)

希望对您有所帮助。

Spring 批处理中没有回滚异常显然指定为

<batch:tasklet>
    <batch:chunk ... />
        <batch:no-rollback-exception-classes>
        <batch:include class="MyRuntimeException"/>
    </batch:no-rollback-exception-classes>
</batch:tasklet>