MyBatis批量插入的五种方式,哪种最强?

news/2024/11/15 22:19:10/

前言

这里列举了MyBatis和MyBatis-Plus常用的五种批量插入的方式,进行了详细的总结归纳。

  • 准备工作
  • MyBatis利用For循环批量插入
  • MyBatis的手动批量提交
  • MyBatis以集合方式批量新增(推荐)
  • MyBatis-Plus提供的SaveBatch方法
  • MyBatis-Plus提供的InsertBatchSomeColumn方法(推荐)

一、准备工作

1、导入pom.xml依赖

<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope>
</dependency><!--Mybatis依赖-->
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.2</version>
</dependency><!--Mybatis-Plus依赖-->
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.2</version>
</dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional>
</dependency>

2、配置yml文件

server:port: 8080spring:datasource:username: mysql用户名password: mysql密码url: jdbc:mysql://localhost:3306/数据库名字?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTCdriver-class-name: com.mysql.cj.jdbc.Drivermybatis:mapper-locations: classpath:mapping/*.xml

3、公用的User类

@Data
public class User {private int id;private String username;private String password;
}

二、MyBatis利用For循环批量插入

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

@Service
public class UserService {@Resourceprivate 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" );}}

2、编写UserMapper接口

@Mapper
public interface UserMapper {Integer insertUsers(User user);
}

3、编写UserMapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//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>

4、进行单元测试

@SpringBootTest
class DemoApplicationTests {@Resourceprivate UserService userService;@Testpublic void insert(){userService.InsertUsers();}}

5、结果输出

一万条数据总耗时:26348ms

三、MyBatis的手动批量提交

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

@Service
public class UserService {@Resourceprivate UserMapper userMapper;@Resourceprivate 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" );}}

2、结果输出

一万条数据总耗时:24516ms

四、MyBatis以集合方式批量新增(推荐)

1、编写UserService服务类

@Service
public class UserService {@Resourceprivate 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" );}}

2、编写UserMapper接口

@Mapper
public interface UserMapper {Integer insertUsers(List<User> userList);
}

3、编写UserMapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//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>

4、输出结果

一万条数据总耗时:521ms

五、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" );}
}

2、编写UserMapper接口

@Mapper
public interface UserMapper extends BaseMapper<User> {}

3、单元测试结果

一万条数据总耗时:24674ms

六、MyBatis-Plus提供的InsertBatchSomeColumn方法(推荐)

1、编写EasySqlInjector 自定义类

public class EasySqlInjector extends DefaultSqlInjector {@Overridepublic 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;}
}

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

@Configuration
public class MybatisPlusConfig {@Beanpublic EasySqlInjector sqlInjector() {return new EasySqlInjector();}
}

3、编写UserService服务类

public class UserService{@Resourceprivate 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" );}
}

4、编写EasyBaseMapper接口

public interface EasyBaseMapper<T> extends BaseMapper<T> {/*** 批量插入 仅适用于mysql** @param entityList 实体列表* @return 影响行数*/Integer insertBatchSomeColumn(Collection<T> entityList);
}

5、编写UserMapper接口

@Mapper
public interface UserMapper<T> extends EasyBaseMapper<User> {}

6、单元测试结果

一万条数据总耗时:575ms


http://www.ppmy.cn/news/717138.html

相关文章

MyBatis 批量插入数据的 3 种方法!

作者 | 王磊 来源 | Java中文社群&#xff08;ID&#xff1a;javacn666&#xff09; 转载请联系授权&#xff08;微信ID&#xff1a;GG_Stone 批量插入功能是我们日常工作中比较常见的业务功能之一&#xff0c;之前我也写过一篇关于《MyBatis Plus 批量数据插入功能&#xff0c…

mybatis遍历

参考&#xff1a;foreach 实现 MyBatis 遍历集合与批量操作数据_点滴记录-CSDN博客_mybatis遍历list SELECT * FROM t_employee WHERE id IN (1, 2, 3, ...) /** 根据传入的 id 集合&#xff0c;查询出对应的员工信息&#xff0c;并使用集合保存信息 */ List<Employee> …

MyBatis 使用 foreach 批量插入

教程 单条语句插入多个值 Mapper public interface UserMapper {void batchSave(List<User> userList); }<insert id"batchSave">insert into user(name, password) values<foreach collection"list" item"user" separator&quo…

MyBatis foreach 标签查询案例 MyBatis 批量插入 MyBatis foreach标签批量插入

MyBatis foreach 标签查询案例 MyBatis 批量插入 MyBatis foreach标签批量插入 一、查询语句 <if test"userNos ! null and userNos ! ">AND a.USER_NO IN<foreach collection"userNos.split(,)" item"e" open"(" close"…

Mybatis 批量插入

insert, update 和 delete 前文我们说到了select标签&#xff0c;以及一些复杂查询的处理。本文我们主要讨论一下Mybatis的批量插入操作。在这之前&#xff0c;我们还是得先了解insert, update 和 delete标签。 <insertid"insertAuthor"parameterType"doma…

美德乐吸奶器怎么样?

美德乐吸奶器中国官网地址为&#xff1a;http://medela.wang&#xff0c;旨在为中国妈妈提供关于美德乐吸奶器产品介绍&#xff0c;美德乐吸奶器售后服务。经过几十年躬耕和发展。美德乐已经赢得了中国妈妈的信赖&#xff0c;下面让我们来看一下妈妈们对美德乐产品的评价。 作为…

mybatis——动态SQL(使用foreach实现批量插入数据)

mybatis——动态SQL&#xff08;使用foreach实现批量插入数据&#xff09; 1、在UserMapper接口类写批量插入数据的接口 void insertList(List<User> list);2、在对应的UserMapper.xml文件里写SQL语句 <mapper namespace"com.xyxy.mapper.UserMapper">…

mybatis 插入大量数据效率对比,foreach插入、SqlSession批量插入、sql插入

使用mybatis插入数据执行效率对比&#xff0c;对比三种方式&#xff08;测试数据库为MySQL&#xff09;&#xff0c; 1 使用 SqlSessionFactory&#xff0c;每一批数据执行一次提交(未开启批处理) 2 使用mybatis-plus框架的insert方法&#xff0c;for循环&#xff0c;每次执行…