1 环境准备

demo 地址:learn-mybatis · Sean/spring-cloud-alibaba - 码云(gitee.com)

1.1 搭建 MyBatis-Plus 环境

  1. 创建 maven springboot 工程
  2. 导入依赖:web 启动器、jdbc、、java 连接 mysql、Lombok、druid 连接池启动器、mybatis-plus 启动器
  3. 编写 yaml 配置文件,配置 druid 数据源、mybatis-plus

注意要点:

  1. mapper 接口继承 BaseMapper<实体类>
  2. service 接口继承 IService<实体类>
  3. service 接口实现类继承 ServiceImpl<mapper 接口, 实体类> 实现 service 接口

1.2 批量插入测试接口

  1. MyBatis 批量插入接口
     @GetMapping("/mybatis-batch-insert")
    public String mybatisBatchInsert(){
    // 开始时间
    long stime = System.currentTimeMillis();
    // 批量插入
    orderService.mySaveBatch(list);
    // 结束时间
    long etime = System.currentTimeMillis();
    return "mybatis 批量插入 1w 条数据的时间: " + (etime - stime) / 1000.0 + "秒";
    }

    Mybatis 的批量插入是调用 mapper 的批量插入接口,使用 标签拼接 sql 进行插入

  2. Mybatis-Plus 批量插入接口
    @GetMapping("/mybatis-batch-insert")
    public String mybatisBatchInsert(){
    // 开始时间
    long stime = System.currentTimeMillis();
    // 批量插入
    orderService.mySaveBatch(list);
    // 结束时间
    long etime = System.currentTimeMillis();
    return "mybatis 批量插入 1w 条数据的时间: " + (etime - stime) / 1000.0 + "秒";
    }

    MyBatis-Plus 的批量插入是调用 mybatis-plus 的 IService 接口的 saveBatch 进行批量插入

1.3 批量更新测试接口

  1. MyBatis 批量更新接口

    @GetMapping("/mybatis-batch-update")
    public String mybatisBatchUpdate(){
    long stime = System.currentTimeMillis();
    orderService.myUpdateBatchById(updateList);
    long etime = System.currentTimeMillis();
    return "mybatis 批量更新 1w 条数据的时间: " + (etime - stime) / 1000.0 + "秒";
    }

    MyBatis 的批量插入是调用 mapper 的批量更新接口,使用 标签拼接 sql 进行更新,是将多个更新语句拼接在同一个 mapper 接口中,需要在数据库连接 url 添加 allowMultiQueries=true 开启多查询

  2. MyBatis-Plus 批量更新接口

    @GetMapping("/mybatis-plus-batch-update")
    public String mybatisPlusBatchUpdate(){
    long stime = System.currentTimeMillis();
    orderService.updateBatchById(updateList);
    long etime = System.currentTimeMillis();
    return "mybatis plus 批量更新 1w 条数据的时间: " + (etime - stime) / 1000.0 + "秒";
    }

    MyBatis -Plus 的批量更新是调用 mybatis-plus 的 IService 接口的 updateBatchById 进行批量更新

2. 性能对比

经过预热,尽量避免了缓存的影响。

2.1 批量插入性能对比

数据量:1w 条数据,每条数据 4 个字段

测试结果:

  • MyBatis:5 次运行平均耗时:0.3212 秒
  • MyBatis-Plus:5次运行平均耗时:1.35 秒
  • MyBatis-Plus(开启批处理):5次运行平均耗时:0.2424 秒

2.2 批量更新性能对比

数据量:1w 条数据,每条数据更新 4 个字段

测试结果:

  • MyBatis:5 次运行平均耗时:1.0378 秒
  • MyBatis-Plus:5次运行平均耗时:1.6448 秒
  • MyBatis-Plus(开启批处理):5次运行平均耗时:0.743 秒

3. 原理探究

3.1 批量插入

3.1.1 MyBatis

MyBatis 的批量插入 xml

<insert id="mySaveBatch">
insert into order_table(id, product_id, total_amount, status) values
<foreach collection="list" separator="," item="item">
(#{item.id}, #{item.productId}, #{item.totalAmount}, #{item.status})
</foreach>
</insert>

通过 标签,将插入的数据拼接成一条 SQL 语句,一次性进行插入操作,拼接完的 SQL 语句如下例子:

insert into order_table(id, product_id, total_amount, status) values(1, 2. 2.0, 1),(2, 2, 2.0, 1);

3.1.2 MyBatis-Plus

MyBatis-Plus 的批量插入本质采用 for 遍历每条数据依次插入,但使用了批处理优化,默认是每 1000 条数据,刷新一次 statement 提交到数据库,执行插入操作。

注意:批处理需要在数据库连接中添加 rewriteBatchedStatements=true 否则 jdbc 驱动在默认情况下会无视executeBatch() 语句

源码如下:

@Transactional(rollbackFor = Exception.class)   // 开启事务
@Override
public boolean saveBatch(Collection<T> entityList, int batchSize) {
String sqlStatement = getSqlStatement(SqlMethod.INSERT_ONE); // 获得插入 statement
// 执行批处理操作
// 参数是:待插入集合,批次大小(默认1000),函数式接口 accept
return executeBatch(entityList, batchSize, (sqlSession, entity) -> sqlSession.insert(sqlStatement, entity));
}
public static <E> boolean executeBatch(Class<?> entityClass, Log log, Collection<E> list, int batchSize, BiConsumer<SqlSession, E> consumer) {
Assert.isFalse(batchSize < 1, "batchSize must not be less than one");
return !CollectionUtils.isEmpty(list) && executeBatch(entityClass, log, sqlSession -> {
int size = list.size();
int idxLimit = Math.min(batchSize, size);
int i = 1;
// 遍历插入
for (E element : list) {
// 调用 sqlSession.insert(sqlStatement, entity));
// 对元素执行插入操作,但此时数据库还没真正执行插入语句
consumer.accept(sqlSession, element);
// 计数达到 1000 或者 集合结束
if (i == idxLimit) {
// 刷新 statement 提交批处理语句,数据库真正执行 SQL
sqlSession.flushStatements();
idxLimit = Math.min(idxLimit + batchSize, size);
}
i++;
}
});
}

3.2 批量更新

3.2.1 MyBatis

MyBatis 的批量更新 xml

<update id="myUpdateBatchById">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update order_table
<set>
product_id = #{item.productId},
total_amount = #{item.totalAmount},
status = #{item.status}
</set>
where id = #{item.id}
</foreach>
</update>

通过 标签,拼接成多条更新的 SQL 语句,一次性提交数据库执行。语句例子如下:

update order_table set product_id = 1, total_amount = 2, status = 1 where id = 1;
update order_table set product_id = 1, total_amount = 2, status = 1 where id = 2;

3.1.2 MyBatis-Plus

MyBatis-Plus 批量更新的原理基本和其批量插入的原理一致,都是调用 executeBatch 执行批处理操作。

4. 优缺点分析

4.1 批量插入

对于批量插入,MyBatis 拼接 SQL 的写法比 MyBatis-Plus 的批量插入方法有明显更高的性能。

但在开启批处理优化之后,MyBatis-Plus 的方法性能更高了。

MyBatis:

  • 优点:性能较高
  • 缺点:在处理大数据量(SQL 语句大于 64MB 时)会报错,MySQL 8.0.33 默认最大 SQL 大小为 64MB

    也要考虑内存异常等问题。

MyBatisPlus:

  • 优点:分组提交,适用于大数据量的处理
  • 缺点:单条插入语句执行,性能较低

总结:

  • 没开启批处理时:10w 数据量以下建议使用 MyBatis、10w 数据量以上建议使用 MyBatis-Plus
  • 开启批处理时:建议使用 MyBatis-Plus

4.2 批量更新

对于批量更新,MyBatis 拼接 SQL 的写法与 MyBatis-Plus 的批量更新方法无明显的性能差别.

大于大数据量,拼接写法甚至容易出现内存耗尽等问题,相比之下 MyBatis-Plus 的方法更优。

总结:建议使用 MyBatis-Plus

对比 MyBatis 和 MyBatis-Plus 批量插入、批量更新的性能和区别的更多相关文章

  1. mybatis 注解的方式批量插入,更新数据

    一,当向数据表中插入一条数据时,一般先检查该数据是否已经存在,如果存在更新,不存在则新增  使用关键字  ON DUPLICATE KEY UPDATE zk_device_id为主键 model  ...

  2. mybatis中批量插入以及更新

    1:批量插入 批量插入就是在预编译的时候,将代码进行拼接,然后在数据库执行 <insert id="batchInsert" parameterType="java ...

  3. java批量插入或更新的问题

    在批量插入或者更新中,setXXX的时候字段类型必须一致.例如:在普通sql中 pstmt8.setBigDecimal(j ,xxx);可以写成pstmt8.setString(j,xxx.toSt ...

  4. C#使用SqlDataAdapter 实现数据的批量插入和更新

    近日由于项目要求在需要实现中型数据的批量插入和更新,晚上无聊,在网上看到看到这样的一个实现方法,特摘抄过来,以便以后可能用到参考. 一.数据的插入 DateTime begin = DateTime. ...

  5. MySQL on duplicate key update 批量插入并更新已存在数据

    业务上经常存在一种现象,需要批量往表中插入多条数据,但在执行过程中,很可能因为唯一键冲突,而导致批量插入失败.因此需要事先判断哪些数据是重复的,哪些是新增的.比较常用的处理方法就是找出已存在的数据,并 ...

  6. springMVC 接收数组参数,mybatis 接收数组参数,mybatis批量插入/批量删除案例

    案例是给一个用户赋予多个权限,多个权限用其对应的主键 id 为参数,组成了 一个id数组,传给springMVC,然后springMVC传给mybatis,然后mybatis批量插入.其实类似的场景还 ...

  7. Mybatis中实现oracle的批量插入、更新

    oracle 实现在Mybatis中批量插入,下面测试可以使用,在批量插入中不能使用insert 标签,只能使用select标签进行批量插入,否则会提示错误 ### Cause: java.sql.S ...

  8. mybatis foreach批量插入数据:Oracle与MySQL区别

    mybatis foreach批量插入数据:Oracle与MySQL不同点: 主要不同点在于foreach标签内separator属性的设置问题: separator设置为","分 ...

  9. 【mybatis】mybatis中批量插入 批量更新 batch 进行insert 和 update,或者切割LIst进行批量操作

    ================================================================== 分别展示 mybatis 批量新增  和 批量更新   的操作: ...

  10. Mybatis 批量插入和更新小例

    SpringBoot配置Mybatis前文有博文,数据库mysql: package com.example.demo.biz.dto; public class User { private int ...

随机推荐

  1. ES5 apply与call详解

    虽然es6已经出台了很多简单的方法替代了apply和call,但是还是有很多老大项目使用到了es5的这些方法,所以对于这些方法的掌握是有必要的 先回顾一下官方对apply.call的诠释 apply方 ...

  2. 【最佳实践】如何设计 RESTful API ?

    良好的 API 设计是一个经常被提及的话题,特别是对于那些试图完善其 API 策略的团队来说.一个设计良好的 API 的好处包括:改进开发者体验.更快速地编写文档以及更高效地推广你的 API.但是,到 ...

  3. Apache Hudi 1.x 版本重磅功能展望与讨论

    Apache Hudi 社区正在对Apache Hudi 1.x版本功能进行讨论,欢迎感兴趣同学参与讨论,PR链接:https://github.com/apache/hudi/pull/8679/f ...

  4. Application of Permutation and Combination

    Reference https://www.shuxuele.com/combinatorics/combinations-permutations.html Online Tool https:// ...

  5. 解决QRCODE生成的二维码微信长按不识别问题

    问题描述 QRcode 生成二维码,展示到页面,微信打开,长按二维码没反应.而直接放二维码图片上去可以识别. 问题原因 手机兼容问题qrcode在页面生成二维码时,会生成一个canvas标签和一个im ...

  6. GPU技术在大规模数据集处理和大规模计算中的应用

    目录 GPU 技术在大规模数据集处理和大规模计算中的应用 随着深度学习在人工智能领域的快速发展,大规模数据处理和大规模计算的需求日益增长.GPU(图形处理器)作为现代计算机的重要部件,被广泛应用于这些 ...

  7. 牛客题解-mixup2混乱的奶牛(状压dp)

    题解-mixup2混乱的奶牛 [原题连接](1026-mixup2混乱的奶牛_2021秋季算法入门班第八章习题:动态规划2 (nowcoder.com)) 题目描述 混乱的奶牛 [Don Piele, ...

  8. 把jar包打成docker镜像并推送到Docker Hub

    1.准备需要的jar包并复制到服务器某个目录下 2.在此目录下,创建Dockerfile的文本文件,并将以下内容添加到文件中: # 基础镜像 FROM openjdk:8-jre # author(可 ...

  9. 《HelloGitHub》第 87 期

    兴趣是最好的老师,HelloGitHub 让你对编程感兴趣! 简介 HelloGitHub 分享 GitHub 上有趣.入门级的开源项目. https://github.com/521xueweiha ...

  10. 这样看C函数才对

    什么是函数?从定义来看,函数就是一段可以重复使用的代码块,比如下面这样 void hanshu() { int a = 0; int b = 3; } 这时候就应该有人要跳出来了,这是什么**!确实, ...