mybatis-plus批量新增更新
本文主要记录高效使用mybatis的批量新增更新功能及使用过程中的优化方式
批量新增的几种方式
forEach循环
此种方式最为低效,测试数据10w耗时30s,代码如下
List<ButlerComment> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
ButlerComment butlerComment = new ButlerComment();
butlerComment.setId(Long.valueOf(i));
butlerComment.setButlerNickName("yangxc");
butlerComment.setContent("hello test contentbutlerCommentService.saveOrUpdateBatchbutlerCommentService.saveOrUpdateBatchbutlerCommentService.saveOrUpdateBatch");
butlerComment.setRemark("butlerCommentService.saveOrUpdateBatchbutlerCommentService.saveOrUpdateBatchbutlerCommentService.saveOrUpdateBatch");
butlerComment.setButlerId(1L);
list.add(butlerComment);
}
list.forEach(butlerComment -> {
butlerCommentService.save(butlerComment);
});
foreach低效的原因为每次都想mysql发送一次,经历建立连接、执行语句、关闭连接等操作
saveBatch批量新增
执行耗时600ms,
butlerCommentService.saveBatch(list);
此种方式mysqlplus默认的批量处理规则为1000条为一个批次,向mysql发送一次而且采用的插入方式为
Preparing: INSERT INTO butler_comment ( id, butler_id, butler_nick_name, content, remark ) VALUES ( ?, ?, ?, ?, ? )
Parameters: 0(Long), 1(Long), yangxc(String), hello test(String), butlerCommentService.(String)
Parameters: 1(Long), 1(Long), yangxc(String), hello test(String), butlerCommentService.(String)
Parameters: 2(Long), 1(Long), yangxc(String), hello test(String), butlerCommentService.(String)
方式,可以通过在yaml配置如下打印日志方式查看执行sql
logging:
level:
com.yangxc.mapper: debug
网上说的在jdbc的url中添加rewriteBatchedStatements=true,并没有实际作用,最后打出的sql同上也是批次提交并不是mysql支持的批量语法insert values(),(),();
saveOrUpdateBatch原理
会判断id是否为空,id不为空查询当前id是否存在记录;不存在保存,存在更新
总结
综上所述其实提供的批量插入方法都不是很高效,下篇文章介绍一下自定义批量操作的高效方式
评论区