2012-03-21 131 views
3

目前我们的代码使用JdbcTemplate的batchUpdate方法来进行批量插入。Spring JdbcTemplate batchUpdate处理异常

我的问题是任何异常的情况下,在更新如何处理它的一个(加入日志只是假设),并继续下一个更新的SQL语句?

还怎么BATCHUPDATE()方法FO的JdbcTemplate处理异常?

这里的代码片段。

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

汉鼎错误是不容易的,而且也没有一个解决问题的办法。这取决于你*想要如何处理它。 – skaffman 2012-03-21 17:18:18

+0

你使用了什么数据库? – alexkasko 2012-03-22 11:14:53

+0

其Oracle数据库。 – minil 2012-03-22 13:13:11

回答

5

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

批量更新行为是undefined in JDBC

如果在间歇更新的命令之一无法正确执行,此方法抛出的BatchUpdateException,和JDBC驱动器可以或者可以不继续处理批处理中剩余的命令。

你应该检查你的DBMS这种行为。

无论如何,BatchUpdateException将在春季被捕获,并在一些清理后作为RuntimeException重新抛出(请参阅实施细节here)。例如 -

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

所以期望“日志错误行唯一的”批量逻辑不能在没有额外的知识有效地实现你的DBMS,它是在批量插入在错误的JDBC驱动程序的行为。

0

我跑进映入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 
      } 

     }