2016-07-27 119 views
2

我想用batchUpdate更新表中数以千计的行。我的要求是:错误处理Spring JdbcTemplate batchUpdate

1)假设一批中有1000条记录。记录无235导致错误。如何找出哪条记录导致错误。

2)假设记录600没有导致更新(原因可能是没有匹配where子句的记录)。如何查找未导致更新的记录?

3)在上述两种情况下,我如何继续处理剩余的记录。

回答

2

长时间搜索和调试后唯一的解决方案是转到BatchUpdateException类并找到负面元素并从MAP中推断出错的插入值。

import java.sql.BatchUpdateException; 
import java.sql.PreparedStatement; 
import java.sql.SQLException; 
import java.sql.Statement; 
import java.util.List; 
import java.util.Map; 


import org.springframework.jdbc.core.BatchPreparedStatementSetter; 
import org.springframework.stereotype.Repository; 
import org.springframework.transaction.annotation.Propagation; 
import org.springframework.transaction.annotation.Transactional; 


@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) 
@Repository("dao_") 
public class YouDao extends CommunDao implements IyouDao { 

    public void bulkInsert(final List<Map<String, String>> map) 
      throws BusinessException { 
     try { 

      String sql = " insert into your_table " + "( aa,bb )" 
        + "values " + "( ?,?)"; 
      BatchPreparedStatementSetter batchPreparedStatementSetter = new BatchPreparedStatementSetter() { 
       @Override 
       public void setValues(PreparedStatement ps, int i) 
         throws SQLException { 
        Map<String, String> bean = map.get(i); 

        ps.setString(1, bean.get("aa")); 
        ps.setString(2, bean.get("bb")); 
        //.. 
        //.. 

       } 

       @Override 
       public int getBatchSize() { 
        return map.size(); 
       } 
      }; 

      getJdbcTemplate().batchUpdate(sql, batchPreparedStatementSetter); 

     } 

     catch (Exception e) { 
      if (e.getCause() instanceof BatchUpdateException) { 
       BatchUpdateException be = (BatchUpdateException) e.getCause(); 
       int[] batchRes = be.getUpdateCounts(); 
       if (batchRes != null && batchRes.length > 0) { 
        for (int index = 0; index < batchRes.length; index++) { 
         if (batchRes[index] == Statement.EXECUTE_FAILED) { 
          logger.error("Error execution >>>>>>>>>>>" 
            + index + " --- , codeFail : " + batchRes[index] 
            + "---, line " + map.get(index)); 
         } 
        } 
       } 
      } 
      throw new BusinessException(e); 
     } 

    } 

} 
+0

我看到你遇到了一个BatchUpdateException,但是当我尝试这样做时,我得到一个语法错误,因为它表示没有任何类中的类实际抛出它,这是文档所承载的。什么引发你的异常? (这就是为什么你正在做的getCause()的东西?) – Steve

-2

INT []行= jdbcTemplate.batchUpdate(TbCareQueryConstant.SQL_UPDATE_BANKDETAILS_OF_USER,新BatchPreparedStatementSe tter(){

..... 代码

}

为( int i = 0; i < rows.length; i ++){

 if(rows[i] == 0){ 


     }  
    } 
+2

欢迎来到堆栈溢出!您的答案只包含(格式不正确) 代码,而缺乏某种解释。我会建议阅读[我如何写一个好的答案](https://stackoverflow.com/help/how-to-answer),然后也许编辑答案。 – FanaticD