Spring JdbcTemplate批量操作数据库

个人总结,转载请注明出处: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     }
原文地址:https://www.cnblogs.com/lidabnu/p/5769732.html