Mybatis批量更新新增

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是否存在记录;不存在保存,存在更新

总结

综上所述其实提供的批量插入方法都不是很高效,下篇文章介绍一下自定义批量操作的高效方式


获取更多相关文章请点击木易成-开发者天地,不定时分享个人技术观点、股票交易经验、生活经历、NBA观点等精彩信息。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值