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

関連する問題