MyBatis-Plus 批量新增
MyBatisPlus的IService接口中,提供的批量新增 .saveBatch()性能较for循环新增,有比较明显的性能提升
原因:
MybatisPlus
的批处理是基于PrepareStatement
的预编译模式,然后批量提交,最终在数据库执行时还是会有多条insert语句,逐条插入数据;
多条insert就会有多次跟数据库的网络交互,还是会消耗资源影响性能;
但是想对批量新增有更加优秀的性能提升,需要对MySql底层处理逻辑进行参数配置,即在application.yml文件中修改配置:rewriteBatchedStatments=true
原因:
MySQL的客户端连接参数中有这样的一个参数:
rewriteBatchedStatements
。顾名思义,就是重写批处理的statement
语句;这个参数的默认值是false,我们需要修改连接参数,将其配置为true
修改项目中的application.yml文件,在jdbc的url后面添加参数
&rewriteBatchedStatements=true
;在
ClientPreparedStatement
的executeBatchInternal
中,有判断rewriteBatchedStatements
值是否为true并重写SQL的功能:
将所有新增重写成一条SQL语句,进行一次网络交互即可执行完成,效率大大提升;
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: root
@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));
}