5

目前我们的代码使用 JdbcTemplate 的 batchUpdate 方法进行批量插入。

我的问题是,如果其中一个更新出现任何异常,如何处理它(假设只是添加日志)并继续执行下一个更新 sql 语句?

还有 JdbcTemplate 的 batchUpdate() 方法如何处理异常?

片段在这里。

    /**
     * Saves the list of <code>Item</code> objects to the database in a batch mode
     * 
     * @param objects
     *    list of objects to save in a batch mode
     */
    public void save(final List<Item> listOfItems) {

        for (List<Debit> list : listOfItems) {
            getJdbcTemplate().batchUpdate(insertItem, new ItemBatchPreparedStatementSetter(list));
        }
    }
4

2 回答 2

7

JdbcTemplate 的 batchUpdate() 方法如何处理异常?

JDBC 中未定义批量更新行为:

如果批量更新中的某个命令未能正确执行,则此方法会抛出 BatchUpdateException,并且 JDBC 驱动程序可能会或可能不会继续处理批处理中剩余的命令。

您应该使用 DBMS 检查此行为。

无论如何,BatchUpdateException将被 spring 捕获并在经过一些清理后作为 RuntimeException 重新抛出(请参阅此处的实现细节)。

所有这些逻辑都将与事务交织在一起 - 例如,如果插入在事务范围内并且您重新抛出RuntimeException事务范围 - 事务(以及所有成功的插入)将被回滚。

因此,如果没有关于 DBMS 的额外知识以及批量插入期间错误的 JDBC 驱动程序行为,就无法有效地实现所需的“仅记录错误行”批处理逻辑。

于 2012-03-22T11:14:16.123 回答
0

我遇到了同样的问题,即 spring jdbc 在出现任何错误记录时停止插入并且不继续插入。以下是我的工作: -

// divide the inputlist into batches and for each batch :-
for (int j = 0; j < resEntlSize; j += getEntlBatchSize()) {
            final List<ResEntlDTO> batchEntlDTOList = resEntlDTOList
                    .subList(
                            j,
                            j + getEntlBatchSize() > resEntlSize ? resEntlSize
                                    : j + getEntlBatchSize());
            TransactionDefinition def = new DefaultTransactionDefinition();
            TransactionStatus status = transactionManager
                    .getTransaction(def);
            try {
                //perform batchupdate for the batch
                transactionManager.commit(status);
            } catch (Exception e) {
                transactionManager.rollback(status);
                //perform single update for the error batch
            }

        }
于 2014-04-15T20:05:42.893 回答