• 10w条数据仅需2秒,浅谈MyBatis批量插入方法


    前言:批量插入功能是我们日常工作中比较常见的业务功能之一,今天学长来一个 MyBatis 批量插入的汇总篇,同时对 3 种实现方法做一个性能测试,以及相应的原理分析。

    先来简单说一下 3 种批量插入功能分别是:

    1. 循环单次插入;
    2. MP 批量插入功能;
    3. 原生批量插入功能。

    准备工作

    开始之前我们先来创建数据库和测试数据,执行的 SQL 脚本如下:

    1. -- ----------------------------
    2. -- 创建数据库
    3. -- ----------------------------
    4. SET NAMES utf8mb4;
    5. SET FOREIGN_KEY_CHECKS = 0;
    6. DROP DATABASE IF EXISTS `testdb`;
    7. CREATE DATABASE `testdb`;
    8. USE `testdb`;
    9. -- ----------------------------
    10. -- 创建 user 表
    11. -- ----------------------------
    12. DROP TABLE IF EXISTS `user`;
    13. CREATE TABLE `user` (
    14. `id` int(11) NOT NULL AUTO_INCREMENT,
    15. `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
    16. `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
    17. `createtime` datetime NULL DEFAULT CURRENT_TIMESTAMP,
    18. PRIMARY KEY (`id`) USING BTREE
    19. ) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;
    20. -- ----------------------------
    21. -- 添加测试数据
    22. -- ----------------------------
    23. INSERT INTO `user` VALUES (1, '赵云', '123456', '2021-09-10 18:11:16');
    24. INSERT INTO `user` VALUES (2, '张飞', '123456', '2021-09-10 18:11:28');
    25. INSERT INTO `user` VALUES (3, '关羽', '123456', '2021-09-10 18:11:34');
    26. INSERT INTO `user` VALUES (4, '刘备', '123456', '2021-09-10 18:11:41');
    27. INSERT INTO `user` VALUES (5, '曹操', '123456', '2021-09-10 18:12:02');
    28. SET FOREIGN_KEY_CHECKS = 1;

    数据库的最终效果如下:

    1.循环单次插入

    接下来我们将使用 Spring Boot 项目,批量插入 10W 条数据来分别测试各个方法的执行时间。

    循环单次插入的(测试)核心代码如下:

    1. import com.example.demo.model.User;
    2. import com.example.demo.service.impl.UserServiceImpl;
    3. import org.junit.jupiter.api.Test;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.boot.test.context.SpringBootTest;
    6. @SpringBootTest
    7. class UserControllerTest {
    8. // 最大循环次数
    9. private static final int MAXCOUNT = 100000;
    10. @Autowired
    11. private UserServiceImpl userService;
    12. /**
    13. * 循环单次插入
    14. */
    15. @Test
    16. void save() {
    17. long stime = System.currentTimeMillis(); // 统计开始时间
    18. for (int i = 0; i < MAXCOUNT; i++) {
    19. User user = new User();
    20. user.setName("test:" + i);
    21. user.setPassword("123456");
    22. userService.save(user);
    23. }
    24. long etime = System.currentTimeMillis(); // 统计结束时间
    25. System.out.println("执行时间:" + (etime - stime));
    26. }
    27. }

    运行以上程序,花费了 88574 毫秒,如下图所示:

    2.MP 批量插入

    MP 批量插入功能核心实现类有三个:UserController(控制器)、UserServiceImpl(业务逻辑实现类)、UserMapper(数据库映射类),它们的调用流程如下:

    注意此方法实现需要先添加 MP 框架,打开 pom.xml 文件添加如下内容:

    1. <dependency>
    2. <groupId>com.baomidou</groupId>
    3. <artifactId>mybatis-plus-boot-starter</artifactId>
    4. <version>mybatis-plus-latest-version</version>
    5. </dependency>

    注意:mybatis-plus-latest-version 表示 MP 框架的最新版本号,可访问 mvnrepository.com/artifact/co… 查询最新版本号,但在使用的时候记得一定要将上面的 “mybatis-plus-latest-version”替换成换成具体的版本号,如 3.4.3 才能正常的引入框架。

    更多 MP 框架的介绍请移步它的官网:baomidou.com/guide/

    ① 控制器实现

    1. import com.example.demo.model.User;
    2. import com.example.demo.service.impl.UserServiceImpl;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. import org.springframework.web.bind.annotation.RestController;
    6. import java.util.ArrayList;
    7. import java.util.List;
    8. @RestController
    9. @RequestMapping("/u")
    10. public class UserController {
    11. @Autowired
    12. private UserServiceImpl userService;
    13. /**
    14. * 批量插入(自定义)
    15. */
    16. @RequestMapping("/mysavebatch")
    17. public boolean mySaveBatch(){
    18. List list = new ArrayList<>();
    19. // 待添加(用户)数据
    20. for (int i = 0; i < 1000; i++) {
    21. User user = new User();
    22. user.setName("test:"+i);
    23. user.setPassword("123456");
    24. list.add(user);
    25. }
    26. return userService.saveBatchCustom(list);
    27. }
    28. }

    ② 业务逻辑层实现

    1. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    2. import com.example.demo.mapper.UserMapper;
    3. import com.example.demo.model.User;
    4. import com.example.demo.service.UserService;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Service;
    7. import java.util.List;
    8. @Service
    9. public class UserServiceImpl extends ServiceImpl,User>
    10. implements UserService {
    11. @Autowired
    12. private UserMapper userMapper;
    13. public boolean saveBatchCustom(List<User> list){
    14. return userMapper.saveBatchCustom(list);
    15. }
    16. }

    ③ 数据持久层实现

    1. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    2. import com.example.demo.model.User;
    3. import org.apache.ibatis.annotations.Mapper;
    4. import java.util.List;
    5. @Mapper
    6. public interface UserMapper extends BaseMapper{
    7. boolean saveBatchCustom(List list);
    8. }

    经过以上代码实现,我们就可以使用 MP 来实现数据的批量插入功能了,但本篇除了具体的实现代码之外,我们还要知道每种方法的执行效率,所以接下来我们来编写 MP 的测试代码。

    MP 性能测试

    1. import com.example.demo.model.User;
    2. import com.example.demo.service.impl.UserServiceImpl;
    3. import org.junit.jupiter.api.Test;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.boot.test.context.SpringBootTest;
    6. import java.util.ArrayList;
    7. import java.util.List;
    8. @SpringBootTest
    9. class UserControllerTest {
    10. // 最大循环次数
    11. private static final int MAXCOUNT = 100000;
    12. @Autowired
    13. private UserServiceImpl userService;
    14. /**
    15. * MP 批量插入
    16. */
    17. @Test
    18. void saveBatch() {
    19. long stime = System.currentTimeMillis(); // 统计开始时间
    20. List<User> list = new ArrayList<>();
    21. for (int i = 0; i < MAXCOUNT; i++) {
    22. User user = new User();
    23. user.setName("test:" + i);
    24. user.setPassword("123456");
    25. list.add(user);
    26. }
    27. // MP 批量插入
    28. userService.saveBatch(list);
    29. long etime = System.currentTimeMillis(); // 统计结束时间
    30. System.out.println("执行时间:" + (etime - stime));
    31. }
    32. }

    以上程序的执行总共花费了 6088 毫秒,如下图所示:

    从上述结果可知,使用 MP 的批量插入功能(插入数据 10W 条),它的性能比循环单次插入的性能提升了 14.5 倍。

    MP 源码分析

    从 MP 和循环单次插入的执行时间我们可以看出,使用 MP 并不是像有些朋友认为的那样,还是循环单次执行的,为了更清楚的说明此问题,我们查看了 MP 的源码。

    MP 的核心实现代码是 saveBatch 方法,此方法的源码如下:

    我们继续跟进 saveBatch 的重载方法:

    从上述源码可以看出,MP 是将要执行的数据分成 N 份,每份 1000 条,每满 1000 条就会执行一次批量插入,所以它的性能要比循环单次插入的性能高很多。

    那为什么要分批执行,而不是一次执行?别着急,当我们看了第 3 种实现方法之后我们就明白了。

    3.原生批量插入

    原生批量插入方法是依靠 MyBatis 中的 foreach 标签,将数据拼接成一条原生的 insert 语句一次性执行的,核心实现代码如下。

    ① 业务逻辑层扩展

    在 UserServiceImpl 添加 saveBatchByNative 方法,实现代码如下:

    1. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    2. import com.example.demo.mapper.UserMapper;
    3. import com.example.demo.model.User;
    4. import com.example.demo.service.UserService;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Service;
    7. import java.util.List;
    8. @Service
    9. public class UserServiceImpl extends ServiceImpl, User>
    10. implements UserService {
    11. @Autowired
    12. private UserMapper userMapper;
    13. public boolean saveBatchByNative(List<User> list) {
    14. return userMapper.saveBatchByNative(list);
    15. }
    16. }

    ② 数据持久层扩展

    在 UserMapper 添加 saveBatchByNative 方法,实现代码如下:

    1. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    2. import com.example.demo.model.User;
    3. import org.apache.ibatis.annotations.Mapper;
    4. import java.util.List;
    5. @Mapper
    6. public interface UserMapper extends BaseMapper {
    7. boolean saveBatchByNative(List list);
    8. }

    ③ 添加 UserMapper.xml

    创建 UserMapper.xml 文件,使用 foreach 标签拼接 SQL,具体实现代码如下:

    1. "1.0" encoding="UTF-8"?>
    2. mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    3. <mapper namespace="com.example.demo.mapper.UserMapper">
    4. <insert id="saveBatchByNative">
    5. INSERT INTO `USER`(`NAME`,`PASSWORD`) VALUES
    6. <foreach collection="list" separator="," item="item">
    7. (#{item.name},#{item.password})
    8. foreach>
    9. insert>
    10. mapper>

    经过以上步骤,我们原生的批量插入功能就实现的差不多了,接下来我们使用单元测试来查看一下此方法的执行效率。

    原生批量插入性能测试

    1. import com.example.demo.model.User;
    2. import com.example.demo.service.impl.UserServiceImpl;
    3. import org.junit.jupiter.api.Test;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.boot.test.context.SpringBootTest;
    6. import java.util.ArrayList;
    7. import java.util.List;
    8. @SpringBootTest
    9. class UserControllerTest {
    10. // 最大循环次数
    11. private static final int MAXCOUNT = 100000;
    12. @Autowired
    13. private UserServiceImpl userService;
    14. /**
    15. * 原生自己拼接 SQL,批量插入
    16. */
    17. @Test
    18. void saveBatchByNative() {
    19. long stime = System.currentTimeMillis(); // 统计开始时间
    20. List<User> list = new ArrayList<>();
    21. for (int i = 0; i < MAXCOUNT; i++) {
    22. User user = new User();
    23. user.setName("test:" + i);
    24. user.setPassword("123456");
    25. list.add(user);
    26. }
    27. // 批量插入
    28. userService.saveBatchByNative(list);
    29. long etime = System.currentTimeMillis(); // 统计结束时间
    30. System.out.println("执行时间:" + (etime - stime));
    31. }
    32. }

    然而,当我们运行程序时却发生了以下情况:

    纳尼?程序的执行竟然报错了。

    缺点分析

    从上述报错信息可以看出,当我们使用原生方法将 10W 条数据拼接成一个 SQL 执行时,由于拼接的 SQL 过大(4.56M)从而导致程序执行报错,因为默认情况下 MySQL 可以执行的最大 SQL(大小)为 4M,所以程序就报错了。

    这就是原生批量插入方法的缺点,也是为什么 MP 需要分批执行的原因,就是为了防止程序在执行时,因为触发了数据库的最大执行 SQL 而导致程序执行报错。

    解决方案

    当然我们也可以通过设置 MySQL 的最大执行 SQL 来解决报错的问题,设置命令如下:

    1. -- 设置最大执行 SQL 为 10M
    2. set global max_allowed_packet=10*1024*1024;

    如下图所示:

    注意:以上命令需要在 MySQL 连接的客户端中执行。

    但以上解决方案仍是治标不治本,因为我们无法预测程序中最大的执行 SQL 到底有多大,那么最普世的方法就是分配执行批量插入的方法了(也就是像 MP 实现的那样)。

    当我们将 MySQL 的最大执行 SQL 设置为 10M 之后,运行以上单元测试代码,执行的结果如下:

    总结

    本文我们介绍了 MyBatis 批量插入的 3 种方法,其中循环单次插入的性能最低,也是最不可取的;使用 MyBatis 拼接原生 SQL 一次性插入的方法性能最高,但此方法可能会导致程序执行报错(触发了数据库最大执行 SQL 大小的限制),所以综合以上情况,可以考虑使用 MP 的批量插入功能。

  • 相关阅读:
    openGauss运维操作命令及其相关介绍
    基于神经网络的自动驾驶,人工智能在无人驾驶
    数据库服务Amozon DynamoDB(入门分享)
    uniapp后台播放音频功能制作
    Redis的特性以及使用场景
    commonjs和esmodule
    Banana Pi BPI-W3 NAS 开源路由器开发板采用瑞芯微 RK3588设计,板载8G内存和32G eMMC存储
    redis 哨兵
    socket can应用程序在发送时,怎么控制是标准帧还是扩展帧?
    暑期留校——状态压缩DP-板子题
  • 原文地址:https://blog.csdn.net/LBWNB_Java/article/details/126901366