Spring JdbcTemplate batchUpdate处理异常 [英] Spring JdbcTemplate batchUpdate handling exceptions

查看:1260
本文介绍了Spring JdbcTemplate batchUpdate处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我们的代码使用JdbcTemplate的batchUpdate方法进行批量插入.

Currently our code uses batchUpdate method of JdbcTemplate to do batch Insertion.

我的问题是,如果其中一个更新存在任何异常,如何处理它(假设仅通过添加日志),然后继续下一个更新sql语句?

My question is in case of any exception in one of the update how to handle it (suppose just by adding the log) and continue with the next update sql statements?

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

Also how batchUpdate() method fo JdbcTemplate handles the exceptions?

此处摘录.

    /**
     * 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));
        }
    }

推荐答案

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

how batchUpdate() method fo JdbcTemplate handles the exceptions?

批处理更新行为是在JDBC中未定义:

如果批处理更新中的命令之一无法正确执行,则此方法将引发BatchUpdateException,并且JDBC驱动程序可能会或可能不会继续处理批处理中的其余命令.

If one of the commands in a batch update fails to execute properly, this method throws a BatchUpdateException, and a JDBC driver may or may not continue to process the remaining commands in the batch.

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

You should check this behavior with your DBMS.

无论如何,BatchUpdateException将在被清理后被spring捕获并重新抛出为RuntimeException(请参阅实现详细信息

Anyway, BatchUpdateException will be caught by spring and rethrown as RuntimeException after some clean up (see implementation details here).

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

All this logic will be interwined with transactions - e.g. if insert is within transaction bounds and you rethrow RuntimeException through transaction bounds - transaction (and all successful inserts with it) will be rolled back.

如果没有其他有关DBMS的知识,并且批处理插入期间错误的JDBC驱动程序行为,那么所需的仅记录错误行"批处理逻辑将无法有效实现.

So desired "log error rows only" batch logic cannot be implemented effectively without additional knowledge about your DBMS and it's JDBC driver behaviour on errors during batch inserts.

这篇关于Spring JdbcTemplate batchUpdate处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆