最近开发中使用了spring的NamedParameterJdbcTemplate的批量更行操作
方法如下
public void insert(Collection entities) {
SqlParameterSource[] params = SqlParameterSourceUtils.createBatch(entities.toArray());
namedJdbcTemplate.batchUpdate(insertSql, params);
}
我们业务的实际需要使用的是
public int batchUpdateBeans(String insertSql, List extends Object> beans) {
int[] results = null;
try {
SqlParameterSource[] params = SqlParameterSourceUtils
.createBatch(beans.toArray());
results = this.namedParameterJdbcTemplate.batchUpdate(insertSql,
params);
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage(), e);
}
return results.length;
}
我们只需要传对应的sql 和封装的集合对象就可以实现批量更新了
如:
public int batchAddSupplyInfo(DUserInfo userInfo, List supplyList) {
logger.info(System.currentTimeMillis() + "@" + userInfo.getAccount() + "#SupplyInfo.batchAddSupplyInfo");
StringBuffer sqlKey = new StringBuffer();
StringBuffer sqlValue = new StringBuffer();
sqlKey.append("insert into supply_info ( ");
sqlValue.append(" values ( ");
sqlKey.append("id, name, lang, industry, "
+ "logo, style, brands, products,"
+ " telphone, contactMan, address, status,"
+ "createBy, createTime, updateBy, updateTime )");
sqlValue.append("seq_supply_info.nextval, :name, :lang, :industry, "
+ ":logo, :style, :brands, :products,"
+ " :telphone, :contactMan, :address, :status,"
+ ":createBy, :createTime, :updateBy, :updateTime )");
sqlKey.append(sqlValue);
return baseDao.batchUpdateBeans(sqlKey.toString(), supplyList);
}
上述代码经过测试没问题。
另外我们可以用namedparameterJdbcTemplate的更新方法,传入sql和map集合即可
public int addBuyerRank(User user, DBuyer buyer) {
StringBuffer sqlKey = new StringBuffer("INSERT INTO BUYER (");
StringBuffer sqlValue = new StringBuffer(" Values( ");
Map paramMap = new HashMap();
sqlKey.append(" id, ");
sqlKey.append(" buyerid, ");
sqlKey.append(" rank, ");
sqlKey.append(" createby, ");
sqlKey.append(" updateby, ");
sqlKey.append(" updatetime) ");
sqlValue.append("seq_buyer_rank");
sqlValue.append(" :buyerid, ");
sqlValue.append(" :rank, ");
sqlValue.append(" :createby, ");
sqlKey.append(" createtime, ");
sqlValue.append(" :createtime, ");
sqlValue.append(" :updateby, ");
sqlValue.append(" :updatetime)");
paramMap.put("buyerid", buyerRank.getBuyerId()) ;
paramMap.put("rank", buyerRank.getRank());
paramMap.put("createby", buyerRank.getCreateBy());
paramMap.put("createtime", buyerRank.getCreateTime());
paramMap.put("updateby", buyerRank.getUpdateBy());
paramMap.put("updatetime", buyerRank.getUpdateTime());
sqlKey.append(sqlValue);
int update = 0;
try {
update = baseDao.getNamedParameterJdbcTemplate().update(sqlKey.toString(), paramMap);
} catch (DataAccessException e) {
}
return update;
}