2016-07-27 131 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