
个人总结,转载请注明出处:http://www.cnblogs.com/lidabnu/p/5769732.html
还是分两部分:解决什么问题和怎么做。
解决什么问题
提升数据操作性能,因为批量操作可以减少网络来回次数。
怎么做
方法1:使用jdbcTempalte的batchUpdate方法,第二个参数传入接口BatchPreparedStatementSetter接口,该接口需要实现两个方法,getBatchSize()用于获得该批数量,setValues(PreapredStatement ps, int i)用于设置每个PreparedStatement,以插入为例:
int batchInsert(final List<Stock> stockList)
{
logger.info("batchInsert() begin, stockList.size="+stockList.size());
int[] updatedCountArray = getJdbcTemplate().batchUpdate("insert into stock(id,code,name) value(?,?,?)", new BatchPreparedStatementSetter() { public void setValues(PreparedStatement ps, int i) throws SQLException {
// TODO Auto-generated method stub
ps.setLong(1, stockList.get(i).getId());//要注意,下标从1开始
ps.setString(2, stockList.get(i).getCode());
ps.setString(3, stockList.get(i).getName());
} public int getBatchSize() { return stockList.size();
}
});
int sumInsertedCount = 0;
for(int a: updatedCountArray)
{
sumInsertedCount+=a;
}
logger.info("batchInsert() end, stockList.size="+stockList.size()+",success inserted "+sumInsertedCount+" records");
return sumInsertedCount;
}
方法2:使用内置的SqlParamterSouce,从上面可以看出,代码还是写起来还是挺麻烦,赋值的时候很明显都是与Bean的属性名称有对应关系的,Spring因此提供了内置的方法来简化开发。因为需要足够的信息判断如何将对象的属性映射到sql中去,因此需要使用NamedJdbcTemplate。
int batchDelete(final List<Stock> stockList)
{
logger.info("batchDelete() begin, codeList.size="+stockList.size());
SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(stockList.toArray());
int[] updatedCountArray = getNamedParameterJdbcTemplate().batchUpdate("delete from stock where code=:code", batch);
int sumInsertedCount = 0;
for(int a: updatedCountArray)
{
sumInsertedCount+=a;
}
logger.info("batchInsert() end, stockList.size="+stockList.size()+",success deleted "+sumInsertedCount+" records");
return sumInsertedCount;
}