1. 项目概述:Spring Boot 3.3万级数据批量插入实战
最近在优化公司后台管理系统时,遇到了用户数据批量导入的性能瓶颈。当需要处理上万条数据插入时,传统的单条插入方式耗时高达3秒以上,这显然无法满足业务需求。经过多种方案对比测试,最终我们实现了将万级数据插入耗时压缩到0.2秒左右的优化效果。
本文将基于Spring Boot 3.3和MyBatis-Plus,分享6种经过实战检验的批量插入方案。每种方案都附有完整代码示例和性能测试数据,这些方案包括:
- JDBC原生批处理
- 自定义SQL批处理
- 单条循环插入(基准对比)
- SQL拼接批量插入
- MyBatis-Plus的saveBatch方法
- 批处理模式+事务管理
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 环境准备与基础配置
2.1 项目依赖配置
首先创建一个Spring Boot 3.3项目,在pom.xml中添加以下核心依赖:
xml复制<dependencies>
<!-- Spring Boot基础依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis-Plus依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.7</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 其他工具类依赖 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
2.2 数据库配置
在application.yml中配置数据库连接和MyBatis-Plus相关参数:
yaml复制spring:
datasource:
url: jdbc:mysql://localhost:3306/batch_demo?useSSL=false&rewriteBatchedStatements=true
username: root
password: yourpassword
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: 20
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImp
