個人總結,轉載請注明出處:http://www.cnblogs.com/lidabnu/p/5769732.html
還是分兩部分:解決什么問題和怎么做。
解決什么問題
提升數據操作性能,因為批量操作可以減少網絡來回次數。
怎么做
方法1:使用jdbcTempalte的batchUpdate方法,第二個參數傳入接口BatchPreparedStatementSetter接口,該接口需要實現兩個方法,getBatchSize()用於獲得該批數量,setValues(PreapredStatement ps, int i)用於設置每個PreparedStatement,以插入為例:
1 int batchInsert(final List<Stock> stockList) 2 { 3 logger.info("batchInsert() begin, stockList.size="+stockList.size()); 4 int[] updatedCountArray = getJdbcTemplate().batchUpdate("insert into stock(id,code,name) value(?,?,?)", new BatchPreparedStatementSetter() { 5 6 public void setValues(PreparedStatement ps, int i) throws SQLException { 7 // TODO Auto-generated method stub 8 ps.setLong(1, stockList.get(i).getId());//要注意,下標從1開始 9 ps.setString(2, stockList.get(i).getCode()); 10 ps.setString(3, stockList.get(i).getName()); 11 } 12 13 public int getBatchSize() { 14 15 return stockList.size(); 16 } 17 }); 18 int sumInsertedCount = 0; 19 for(int a: updatedCountArray) 20 { 21 sumInsertedCount+=a; 22 } 23 logger.info("batchInsert() end, stockList.size="+stockList.size()+",success inserted "+sumInsertedCount+" records"); 24 return sumInsertedCount; 25 }
方法2:使用內置的SqlParamterSouce,從上面可以看出,代碼還是寫起來還是挺麻煩,賦值的時候很明顯都是與Bean的屬性名稱有對應關系的,Spring因此提供了內置的方法來簡化開發。因為需要足夠的信息判斷如何將對象的屬性映射到sql中去,因此需要使用NamedJdbcTemplate。
1 int batchDelete(final List<Stock> stockList) 2 { 3 logger.info("batchDelete() begin, codeList.size="+stockList.size()); 4 SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(stockList.toArray()); 5 int[] updatedCountArray = getNamedParameterJdbcTemplate().batchUpdate("delete from stock where code=:code", batch); 6 int sumInsertedCount = 0; 7 for(int a: updatedCountArray) 8 { 9 sumInsertedCount+=a; 10 } 11 logger.info("batchInsert() end, stockList.size="+stockList.size()+",success deleted "+sumInsertedCount+" records"); 12 return sumInsertedCount; 13 }
