这几天做了一个excel导入的功能,习惯使然做的就是单条循环插入,但是查询相关文章后发现在批量插入时功能点固然要完成,但是效率还是要兼顾的,这样总结几总不同方式的批量插入方式
1.单条循环插入,代码如下:
for (int i = 0; i < list.size(); i++) {
Object object = list.get(i);
ExcelPsj excelPsj = (ExcelPsj) object;
Psj psj = new Psj();
BeanUtils.copyProperties(excelPsj,psj);
psj.setCreateTime(new Date());
psj.setDelFlag(CommonConstants.STR_NUM_ZERO);
psj.setStatus("wait");
psj.setSource(CommonConstants.STR_NUM_ONE);
psj.save();
}
此种代码是最简单常用的循环插入方式,若只为完成此功能来写代码,则一般会采用此种方式.但该方法耗时长,效率低.
2.拼接sql循环插入
String sql1 = "insert into pt_log " +
"(id,log_type,request_method,request_uri,request_ip,action_method,action_params," +
"action_result,action_error,user_id,user_name,action_time)" +
"value (?,?,?,?,?,?,?,?,?,?,?,?)";
Object[] data = new Object[]{
UUID.randomUUID().toString(),systemLog.getLogType(),systemLog.getRequestMethod(),
systemLog.getRequestUri(),systemLog.getRequestIp(),systemLog.getActionMethod(),
systemLog.getActionParams(),systemLog.getActionResult(),systemLog.getActionError(),
systemLog.getUserId(),systemLog.getUserName(),systemLog.getActionTime()
};
或者
INSERT INTO project_item VALUES
<foreach collection="list" item="item" index="index" separator=",">
(#{item.projectCode},#{item.projectId},#{item.projectName},#{item.projectType},#{item.status},
#{item.isMain},#{item.planId},#{item.planName},#{item.year},#{item.content},#{item.opinion},
#{item.source},#{item.preCode},#{item.preName},#{item.isPackage},#{item.packageId},
#{item.type}</foreach>
经测,拼接所用耗时小于单条循环插入,效率方面还可.缺点也是显而易见,确实是拼的够呛,稍微不注意的话,无限GG,无限调试也很难发现是少了个文号还是逗号,发现的时候心里只有无数个xxx!
3.通过sqlSessionFactory实现批量插入,代码如下:
@Resource
private SqlSessionFactory sqlSessionFactory;
//该简略就简略
.......
......也许无数行代码.....
//开启批处理(SIMPLE,REUSE,BATCH),测试 BATCH 预处理提交最优
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
try {
//获取 Mapper 代理对象
xxxxMapper xxxMapper = sqlSession.getMapper(xxxxMapper.class);
for (int i = 2; i <= count; i++) {
CauseProject capt = new CauseProject()
capt.setName(name);
capt.setproName(proName);
capt.setType(type);
capt.setMain(main);
capt.setStartTime(startTime);
capt.setEndTime(endTime);
capt.setCreator(currentUserId);
xxxMapper.insert(capt);
if(i!=0 && i/100==0){ //每一百条提交一次
sqlSession.commit();
}
sqlSession.commit();
catch (Exception e){
sqlSession.rollback();
return false;
}finally {
if(sqlSession != null){
sqlSession.close();
}
}
}
此方式是把sql放入数据库预编译,接收参数后一次运行,打印一次sql, 比单条循环插入代码量会多,其优势体现在效率方面,故此种方式不失为最佳方法,有助于提升代码质量.
以上是近期总结的批量的方式,为以后查看特此记下,如部分有误请小伙伴们加以指正,或者有更好的方法总结也请分享共同学习~