• MyBatis批量插入的五种方式


    一:预备工作

    1:pom依赖:

    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <scope>runtimescope>
    dependency>
    
    
    <dependency>
        <groupId>org.mybatis.spring.bootgroupId>
        <artifactId>mybatis-spring-boot-starterartifactId>
        <version>2.2.2version>
    dependency>
    
    
    <dependency>
        <groupId>com.baomidougroupId>
        <artifactId>mybatis-plus-boot-starterartifactId>
        <version>3.5.2version>
    dependency>
    
    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <optional>trueoptional>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    2:配置yml文件

    server:
      port: 8080
     
    spring:
      datasource:
        username: mysql用户名
        password: mysql密码
        url: jdbc:mysql://localhost:3306/数据库名字?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
        driver-class-name: com.mysql.cj.jdbc.Driver
     
    mybatis:
      mapper-locations: classpath:mapping/*.xml
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    3:公用的User类:

    @Data
    public class User {
     
        private int id;
        private String username;
        private String password;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    二、不同的实现方法

    1:MyBatis利用For循环批量插入

    (1)、编写UserService服务类,测试一万条数据耗时情况

    @Service
    public class UserService {
     
        @Resource
        private UserMapper userMapper;
     
        public void InsertUsers(){
            long start = System.currentTimeMillis();
            for(int i = 0 ;i < 10000; i++) {
                User user = new User();
                user.setUsername("name" + i);
                user.setPassword("password" + i);
                userMapper.insertUsers(user);
            }
            long end = System.currentTimeMillis();
            System.out.println("一万条数据总耗时:" + (end-start) + "ms" );
        }
     
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    (2)、编写UserMapper接口

    @Mapper
    public interface UserMapper {
     
        Integer insertUsers(User user);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    (3)、编写UserMapper.xml文件

    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.ithuang.demo.mapper.UserMapper">
        <insert id="insertUsers">
            INSERT INTO user (username, password)
            VALUES(#{username}, #{password})
        insert>
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    (4)、进行单元测试

    @SpringBootTest
    class DemoApplicationTests {
     
        @Resource
        private UserService userService;
     
        @Test
        public void insert(){
            userService.InsertUsers();
        }
     
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    (5)、结果输出

    一万条数据总耗时:26348ms

    2:MyBatis的手动批量提交

    (1)、其他保持不变,Service层作稍微的变化

    @Service
    public class UserService {
     
        @Resource
        private UserMapper userMapper;
     
        @Resource
        private SqlSessionTemplate sqlSessionTemplate;
     
        public void InsertUsers(){
            //关闭自动提交
            SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            long start = System.currentTimeMillis();
            for(int i = 0 ;i < 10000; i++) {
                User user = new User();
                user.setUsername("name" + i);
                user.setPassword("password" + i);
                userMapper.insertUsers(user);
            }
            sqlSession.commit();
            long end = System.currentTimeMillis();
            System.out.println("一万条数据总耗时:" + (end-start) + "ms" );
        }
     
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    (2)、结果输出

    一万条数据总耗时:24516ms

    3:MyBatis以集合方式批量新增(推荐)

    (1)、编写UserService服务类

    @Service
    public class UserService {
     
        @Resource
        private UserMapper userMapper;
     
        public void InsertUsers(){
            long start = System.currentTimeMillis();
            List<User> userList = new ArrayList<>();
            User user;
            for(int i = 0 ;i < 10000; i++) {
                user = new User();
                user.setUsername("name" + i);
                user.setPassword("password" + i);
                userList.add(user);
            }
            userMapper.insertUsers(userList);
            long end = System.currentTimeMillis();
            System.out.println("一万条数据总耗时:" + (end-start) + "ms" );
        }
     
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    (2)、编写UserMapper接口

    @Mapper
    public interface UserMapper {
     
        Integer insertUsers(List<User> userList);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    (3)、编写UserMapper.xml文件

    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.ithuang.demo.mapper.UserMapper">
        <insert id="insertUsers">
            INSERT INTO user (username, password)
            VALUES
            <foreach collection ="userList" item="user" separator =",">
                (#{user.username}, #{user.password})
            foreach>
        insert>
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    (4)、输出结果

    一万条数据总耗时:521ms

    4:MyBatis-Plus提供的SaveBatch方法

    (1)、编写UserService服务

    @Service
    public class UserService extends ServiceImpl<UserMapper, User> implements IService<User> {
     
        public void InsertUsers(){
            long start = System.currentTimeMillis();
            List<User> userList = new ArrayList<>();
            User user;
            for(int i = 0 ;i < 10000; i++) {
                user = new User();
                user.setUsername("name" + i);
                user.setPassword("password" + i);
                userList.add(user);
            }
            saveBatch(userList);
            long end = System.currentTimeMillis();
            System.out.println("一万条数据总耗时:" + (end-start) + "ms" );
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    (2)、编写UserMapper接口

    @Mapper
    public interface UserMapper extends BaseMapper<User> {
     
    }
    
    • 1
    • 2
    • 3
    • 4

    (3)、单元测试结果

    一万条数据总耗时:24674ms

    5:MyBatis-Plus提供的InsertBatchSomeColumn方法(推荐)

    (1)、编写EasySqlInjector 自定义类

    public class EasySqlInjector extends DefaultSqlInjector {
     
     
        @Override
        public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
            // 注意:此SQL注入器继承了DefaultSqlInjector(默认注入器),调用了DefaultSqlInjector的getMethodList方法,保留了mybatis-plus的自带方法
            List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
            methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));
            return methodList;
        }
     
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    (2)、定义核心配置类注入此Bean

    @Configuration
    public class MybatisPlusConfig {
     
        @Bean
        public EasySqlInjector sqlInjector() {
            return new EasySqlInjector();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    (3)、编写UserService服务类

    public class UserService{
     
        @Resource
        private UserMapper userMapper;
        public void InsertUsers(){
            long start = System.currentTimeMillis();
            List<User> userList = new ArrayList<>();
            User user;
            for(int i = 0 ;i < 10000; i++) {
                user = new User();
                user.setUsername("name" + i);
                user.setPassword("password" + i);
                userList.add(user);
            }
            userMapper.insertBatchSomeColumn(userList);
            long end = System.currentTimeMillis();
            System.out.println("一万条数据总耗时:" + (end-start) + "ms" );
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    (4)、编写EasyBaseMapper接口

    public interface EasyBaseMapper<T> extends BaseMapper<T> {
        /**
         * 批量插入 仅适用于mysql
         *
         * @param entityList 实体列表
         * @return 影响行数
         */
        Integer insertBatchSomeColumn(Collection<T> entityList);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    (5)、编写UserMapper接口

    @Mapper
    public interface UserMapper<T> extends EasyBaseMapper<User> {
        
    }
    
    • 1
    • 2
    • 3
    • 4

    (6)、单元测试结果

    一万条数据总耗时:575ms

  • 相关阅读:
    vue中keep-alive的作用
    MySql数据库实现注册登录及个人信息查询的数据库设计
    sudo+vim+g++/gcc+makefile+进度条
    解决plt.imshow()不显示图片cv2.imshw()不显示图片
    Linux驱动移植USB网卡r8156驱动(详细)总结
    Mybatis入门之MyBatisX插件
    「Java开源系统」 FEBS Cloud 微服务权限系统开源系统
    css-边框流水线
    ESPRIT 2019初学到走心机编程视频教程
    冰蝎的原理与安装使用
  • 原文地址:https://blog.csdn.net/justleavel/article/details/128206669