代码拉取完成,页面将自动刷新
MySQL的JDBC连接的url中要加rewriteBatchedStatements参数,并保证5.1.13以上版本的驱动,才能实现高性能的批量插入。MySQL JDBC驱动在默认情况下会无视executeBatch()语句,把我们期望批量执行的一组sql语句拆散,一条一条地发给MySQL数据库,批量插入实际上是单条插入,直接造成较低的性能。只有把rewriteBatchedStatements参数置为true, 驱动才会帮你批量执行SQL,另外这个选项对INSERT/UPDATE/DELETE都有效
mybatis-plus批操作mysql时,若没开启rewriteBatchedStatements,则和逐条插入是一样的,性能较低,建议开启
在连接mysql的jdbc url后加上rewriteBatchedStatements=true
即可
# 未开启rewriteBatchedStatements
#spring.datasource.url=jdbc:mysql://localhost:3306/demo?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true
# 开启rewriteBatchedStatements
spring.datasource.url=jdbc:mysql://localhost:3306/demo?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true
spring.datasource.username=root
spring.datasource.password=dengshuai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
测试代码
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.samples.batch.entity.SysDeptPO;
import com.baomidou.mybatisplus.samples.batch.server.SysDeptService;
import com.ideaaedi.commonds.chars.CharUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@SpringBootTest
public class BatchTest {
@Resource
private SysDeptService sysDeptService;
private static final int SIZE = 100000;
List<SysDeptPO> list = new ArrayList<>(SIZE);
@BeforeEach
private void prepareData() {
for (int i = 0; i < SIZE; i++) {
list.add(
SysDeptPO
.builder()
.id(IdWorker.getId())
.deptName(new String(CharUtil.generateCharArr(10)))
.pid(IdWorker.getId())
.deptPath(new String(CharUtil.generateCharArr(30)))
.build()
);
}
}
@Test
public void aInsert() throws InterruptedException {
int size = list.size();
long start = System.currentTimeMillis();
sysDeptService.saveBatch(list);
long end = System.currentTimeMillis();
TimeUnit.SECONDS.sleep(5);
System.err.printf("插入%d条数据,耗时%d毫秒.", size, end - start);
TimeUnit.SECONDS.sleep(5);
}
}
测试结论
未开启rewriteBatchedStatements,执行三次批操作:
第一次:插入100000条数据,耗时12380毫秒.
第二次:插入100000条数据,耗时12051毫秒.
第三次:插入100000条数据,耗时12525毫秒.
开启rewriteBatchedStatements,执行三次批操作:
第一次:插入100000条数据,耗时2827毫秒.
第二次:插入100000条数据,耗时3238毫秒.
第三次:插入100000条数据,耗时3067毫秒.
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。