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