一.批量新增
IService为我们提供了批量新增的方法,saveBatch方法用来将一个集合中的值进行批量插入。下面我们就来探究一下它相对于普通的逐条新增效果能提升多少。
首先我们来看逐条新增:
private User buildUser(int i) {User user = new User();user.setUsername("user_" + i);user.setPassword("123");user.setPhone("" + (18688190000L + i));user.setBalance(2000);user.setInfo("{\"age\": 24, \"intro\": \"英文老师\", \"gender\": \"female\"}");user.setCreateTime(LocalDateTime.now());user.setUpdateTime(user.getCreateTime());return user;
}
我们准备一段代码,该段代码用来创建一个user对象。
下面我们调用这段代码,将100000条数据加入到数据库中。
@Test
void testSaveOneByOne() {long b = System.currentTimeMillis();for (int i = 1; i <= 100000; i++) {userService.save(buildUser(i));}long e = System.currentTimeMillis();System.out.println("耗时:" + (e - b));
}
查看用时,我们发现共计用时233925ms。

为什么花费了这么长时间?因为每次执行save方法都会执行一次insert语句(insert into ... (... , ... , ...) values (? , ?, ? ,? ..., ?))。并且会访问一次数据库,每次访问数据库都是一次请求,因此会导致大量访问数据库造成性能降低。
接着再看批量新增
@Test
void testSaveBatch() {// 准备10万条数据List<User> list = new ArrayList<>(1000);long b = System.currentTimeMillis();for (int i = 1; i <= 100000; i++) {list.add(buildUser(i));// 每1000条批量插入一次if (i % 1000 == 0) {userService.saveBatch(list);list.clear();}}long e = System.currentTimeMillis();System.out.println("耗时:" + (e - b));
}

提升了将近10倍。为什么呢?因为MybatisPlus
的批处理是基于PrepareStatement
的预编译模式,然后批量提交,最终在数据库执行时还是会有多条insert语句,逐条插入数据。SQL类似这样:
Preparing: INSERT INTO user ( username, password, phone, info, balance, create_time, update_time ) VALUES ( ?, ?, ?, ?, ?, ?, ? )
Parameters: user_1, 123, 18688190001, "", 2000, 2023-07-01, 2023-07-01
Parameters: user_2, 123, 18688190002, "", 2000, 2023-07-01, 2023-07-01
Parameters: user_3, 123, 18688190003, "", 2000, 2023-07-01, 2023-07-01
也就是说MybatisPlus减少了访问数据库请求的次数,由原来的100000次变为了100次。但是仍然是执行了多条SQL语句。有没有一种办法使其能够执行1条SQL语句就完成100000条内容的插入呢?
答案是有,我们只要能构造这样的SQL语句,就能完成。
INSERT INTO user ( username, password, phone, info, balance, create_time, update_time )
VALUES
(user_1, 123, 18688190001, "", 2000, 2023-07-01, 2023-07-01),
(user_2, 123, 18688190002, "", 2000, 2023-07-01, 2023-07-01),
(user_3, 123, 18688190003, "", 2000, 2023-07-01, 2023-07-01),
(user_4, 123, 18688190004, "", 2000, 2023-07-01, 2023-07-01);
该怎么做呢?
MySQL的客户端连接参数中有这样的一个参数:rewriteBatchedStatements
。顾名思义,就是重写批处理的statement
语句。参考文档:
https://dev.mysql.com/doc/connector-j/en/connector-j-connp-props-performance-extensions.html
这个参数的默认值是false,我们需要修改连接参数,将其配置为true。修改项目中的application.yml文件,在jdbc的url后面添加参数&rewriteBatchedStatements=true
:
spring:datasource:url: jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=truedriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: MySQL123
再次测试插入10万条数据,可以发现速度有非常明显的提升:

原理如下:
在ClientPreparedStatement
的executeBatchInternal
中,有判断rewriteBatchedStatements
值是否为true并重写SQL的功能:
最终,SQL被重写了:

重写成了我们希望的样子,这样就能实现一次SQL执行,一次访问。