Spring JdbcTemplate batchUpdate处理异常

标签 spring jdbc jdbctemplate spring-jdbc batch-updates

当前,我们的代码使用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));
        }
    }

最佳答案

how batchUpdate() method fo JdbcTemplate handles the exceptions?



批处理更新行为是undefined in 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检查此行为。

无论如何,BatchUpdateException将被spring捕获,并在进行一些清理后重新抛出为RuntimeException(请参阅实现细节here)。

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

因此,如果没有其他有关DBMS的知识,并且批处理插入期间错误的JDBC驱动程序行为,则无法有效地实现所需的“仅日志错误行”批处理逻辑。

关于Spring JdbcTemplate batchUpdate处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9809503/

相关文章:

mysql - 绑定(bind)参数以在查询中插入常量?

java.sql.SQLException : Invalid column name 异常

tomcat 中的 Java Web 应用程序会定期卡住

java - 如何将 url 作为 @PathVariable 传递给 spring RestController?

java - 如何在没有java的情况下运行SQL命令?

java - 在企业 Java 应用程序中,SQL 位于何处?

java - Spring jdbcTemplate Junit

java - Spring 3.1 : How do I inject a bean created in a different configuration class

java - WEB-INF/jsp 中包含更多文件夹的 viewResolver 在 spring 中不起作用

java - 使用 Java 将变量、数组插入 MySQM 数据库