news 2026/4/12 11:30:55

MyBatis 批量插入从5分钟缩短到3秒?我的三个关键优化

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
MyBatis 批量插入从5分钟缩短到3秒?我的三个关键优化

上周接了个数据迁移的活,要把10万条数据从老系统导入新系统。

写了个简单的批量插入,跑起来一看——5分钟。

领导说太慢了,能不能快点?

折腾了一下午,最后优化到3秒,记录一下过程。

最初的代码(5分钟)

最开始写的很简单,foreach循环插入:

// 方式1:循环单条插入(最慢) for (User user : userList) { userMapper.insert(user); }

10万条数据,每条都要走一次网络请求、一次SQL解析、一次事务提交。

算一下:假设每条插入需要3ms,10万条就是300秒 = 5分钟。

这是最蠢的写法,但我见过很多项目都这么写。

第一次优化:批量SQL(30秒)

把循环插入改成批量SQL:

<!-- Mapper.xml --> <insert id="batchInsert"> INSERT INTO user (name, age, email) VALUES <foreach collection="list" item="item" separator=","> (#{item.name}, #{item.age}, #{item.email}) </foreach> </insert> // 分批插入,每批1000条 int batchSize = 1000; for (int i = 0; i < userList.size(); i += batchSize) { int end = Math.min(i + batchSize, userList.size()); List<User> batch = userList.subList(i, end); userMapper.batchInsert(batch); }

从5分钟降到30秒,提升10倍。

原理:一条SQL插入多条数据,减少网络往返次数。

但还有问题:30秒还是太慢。

第二次优化:JDBC批处理(8秒)

MySQL有个参数叫rewriteBatchedStatements,开启后可以把多条INSERT合并成一条。

第一步:修改数据库连接URL

jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true

第二步:使用MyBatis的批处理模式

@Autowired private SqlSessionFactory sqlSessionFactory; public void batchInsertWithExecutor(List<User> userList) { try (SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH)) { UserMapper mapper = sqlSession.getMapper(UserMapper.class); int batchSize = 1000; for (int i = 0; i < userList.size(); i++) { mapper.insert(userList.get(i)); if ((i + 1) % batchSize == 0) { sqlSession.flushStatements(); sqlSession.clearCache(); } } sqlSession.flushStatements(); sqlSession.commit(); } }

从30秒降到8秒。

原理:ExecutorType.BATCH模式下,MyBatis会缓存SQL,最后一次性发送给数据库执行。配合rewriteBatchedStatements=true,MySQL驱动会把多条INSERT合并。

第三次优化:多线程并行(3秒)

8秒还是不够快,上多线程:

public void parallelBatchInsert(List<User> userList) { int threadCount = 4; // 根据数据库连接池大小调整 int batchSize = userList.size() / threadCount; ExecutorService executor = Executors.newFixedThreadPool(threadCount); List<Future<?>> futures = new ArrayList<>(); for (int i = 0; i < threadCount; i++) { int start = i * batchSize; int end = (i == threadCount - 1) ? userList.size() : (i + 1) * batchSize; List<User> subList = userList.subList(start, end); futures.add(executor.submit(() -> { batchInsertWithExecutor(subList); })); } // 等待所有任务完成 for (Future<?> future : futures) { try { future.get(); } catch (Exception e) { thrownew RuntimeException(e); } } executor.shutdown(); }

从8秒降到3秒。

注意事项:

  • 线程数不要超过数据库连接池大小
  • 如果需要事务一致性,这个方案不适用
  • 要考虑主键冲突的问题

优化效果对比

方案耗时提升倍数
循环单条插入300秒基准
批量SQL30秒10倍
JDBC批处理8秒37倍
多线程并行3秒100倍

踩过的坑

坑1:foreach拼接SQL过长

<foreach collection="list" item="item" separator=",">

如果一次插入太多条,SQL会非常长,可能超过max_allowed_packet限制。

解决:分批插入,每批500-1000条。

坑2:rewriteBatchedStatements不生效

检查几个点:

  • URL参数是否正确:rewriteBatchedStatements=true
  • 是否使用了ExecutorType.BATCH
  • MySQL驱动版本是否太旧

坑3:自增主键返回问题

批量插入时想获取自增主键:

<insert id="batchInsert" useGeneratedKeys="true" keyProperty="id">

注意:rewriteBatchedStatements=true时,自增主键返回可能有问题,需要升级MySQL驱动到8.0.17+。

坑4:内存溢出

10万条数据一次性加载到内存,可能OOM。

解决:分页读取 + 分批插入。

int pageSize = 10000; int total = countTotal(); for (int i = 0; i < total; i += pageSize) { List<User> page = selectByPage(i, pageSize); batchInsertWithExecutor(page); }

最终方案代码

@Service publicclass BatchInsertService { @Autowired private SqlSessionFactory sqlSessionFactory; /** * 高性能批量插入 * 10万条数据约3秒 */ public void highPerformanceBatchInsert(List<User> userList) { if (userList == null || userList.isEmpty()) { return; } int threadCount = Math.min(4, Runtime.getRuntime().availableProcessors()); int batchSize = (int) Math.ceil((double) userList.size() / threadCount); ExecutorService executor = Executors.newFixedThreadPool(threadCount); CountDownLatch latch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { int start = i * batchSize; int end = Math.min((i + 1) * batchSize, userList.size()); if (start >= userList.size()) { latch.countDown(); continue; } List<User> subList = new ArrayList<>(userList.subList(start, end)); executor.submit(() -> { try { doBatchInsert(subList); } finally { latch.countDown(); } }); } try { latch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } executor.shutdown(); } private void doBatchInsert(List<User> userList) { try (SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) { UserMapper mapper = sqlSession.getMapper(UserMapper.class); for (int i = 0; i < userList.size(); i++) { mapper.insert(userList.get(i)); if ((i + 1) % 1000 == 0) { sqlSession.flushStatements(); sqlSession.clearCache(); } } sqlSession.flushStatements(); sqlSession.commit(); } } }

总结

优化点关键配置
批量SQLforeach拼接,分批1000条
JDBC批处理rewriteBatchedStatements=true+ExecutorType.BATCH
多线程线程数 ≤ 连接池大小

核心原则:减少网络往返 + 减少事务次数 + 并行处理。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/3 22:33:39

工业AI大模型:当工厂开始“深度思考”,一场静默的革命正在发生

凌晨三点&#xff0c;重庆某汽车零部件工厂的冲压产线突然响起刺耳的报警声。在过去&#xff0c;这意味着当班工程师需要一头扎进浩如烟海的故障手册与历史工单中&#xff0c;凭借经验和直觉摸索两小时以上。而此刻&#xff0c;系统在不到一秒的时间内&#xff0c;从后台调取了…

作者头像 李华
网站建设 2026/4/8 9:19:02

【强烈收藏】AI大模型发展史:从规则式AI到智能体应用的全方位解读

本文系统梳理了AI从诞生至今的发展历程&#xff0c;分为初生期(1956-1989)、成长期(1990-2016)和爆发期(2017年至今)三个阶段。从最初的规则式AI到基于机器学习的统计式AI&#xff0c;再到以Transformer架构为基础的大模型AI&#xff0c;技术不断演进。文章详细介绍了大模型、多…

作者头像 李华
网站建设 2026/4/11 8:50:31

AI Agent:2026年AI生态革命,开发者的收藏级技术指南

AI Agent 是2026年AI生态的核心概念&#xff0c;它指的是一个具备自主决策、规划和执行能力的数字实体&#xff0c;不再局限于简单的问答或生成式AI&#xff0c;而是能像人类员工一样处理复杂任务。简单来说&#xff0c;Agent 能理解用户意图、分解目标成步骤、调用外部工具或数…

作者头像 李华
网站建设 2026/4/4 6:59:01

换热站程序组态系统开发记录

换热站程序组态系统&#xff0c;2个循环泵&#xff0c;2个补水泵&#xff0c;循环泵与补水泵采用一用一备&#xff0c;按设置时间自动切换&#xff0c;CAD图纸 硬件&#xff1a;昆仑通泰触摸屏和西门子200smart供参考最近搞了个换热站程序组态系统&#xff0c;跟大家分享分享过…

作者头像 李华
网站建设 2026/4/9 22:07:03

SPH 与 DEM 方法系统对比

[toc0] SPH 与 DEM 方法系统对比&#xff1a;异同与耦合应用 一、核心本质差异 维度SPH (Smoothed Particle Hydrodynamics)DEM (Discrete Element Method)物理本质连续介质近似&#xff1a;粒子代表连续流体/固体的"质量点"&#xff0c;通过核函数重构场变量离散…

作者头像 李华
网站建设 2026/4/8 12:43:38

小白也能看懂!LLM强化学习(RL)核心解析+PPO训练全流程

对于刚入门大模型的程序员和小白来说&#xff0c;强化学习&#xff08;RL&#xff09;是理解LLM训练逻辑的关键一环——2026年大模型技术持续迭代&#xff0c;RL与LLM的结合愈发紧密&#xff0c;掌握其核心框架和实操逻辑&#xff0c;能快速提升对大模型训练的认知。本文将用通…

作者头像 李华