news 2026/4/4 16:46:04

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

作者头像

张小明

前端开发工程师

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

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

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

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

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

01

最初的代码(5分钟)

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

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

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

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

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

02

次优化:批量SQL(30秒)

把循环插入改成批量SQL:

<!-- Mapper.xml --> <insertid="batchInsert"> INSERT INTO user (name, age, email) VALUES <foreachcollection="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秒还是太慢。

03

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

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

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

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

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

@Autowired private SqlSessionFactory sqlSessionFactory; publicvoidbatchInsertWithExecutor(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合并。

04

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

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

publicvoidparallelBatchInsert(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秒。

注意事项:

  • 线程数不要超过数据库连接池大小

  • 如果需要事务一致性,这个方案不适用

  • 要考虑主键冲突的问题

05

优化效果对比

方案

耗时

提升倍数

循环单条插入

300秒

基准

批量SQL

30秒

10倍

JDBC批处理

8秒

37倍

多线程并行

3秒

100倍

06

踩过的坑

坑1:foreach拼接SQL过长

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

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

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

坑2:rewriteBatchedStatements不生效

检查几个点:

  • URL参数是否正确: rewriteBatchedStatements=true

  • 是否使用了 ExecutorType.BATCH

  • MySQL驱动版本是否太旧

坑3:自增主键返回问题

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

<insertid="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); }

07

最终方案代码

@Service publicclassBatchInsertService{ @Autowired private SqlSessionFactory sqlSessionFactory; /** * 高性能批量插入 * 10万条数据约3秒 */ publicvoidhighPerformanceBatchInsert(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(); } privatevoiddoBatchInsert(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(); } } }

08

总结

优化点

关键配置

批量SQL

foreach拼接,分批1000条

JDBC批处理

rewriteBatchedStatements=true+ExecutorType.BATCH

多线程

线程数 ≤ 连接池大小

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

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

算法竞赛中cin常用的成员函数

目录1. cin.get() - 单个字符读取&#xff08;含空白字符&#xff09;核心作用竞赛常用写法典型竞赛场景注意事项2. cin.ignore() - 缓冲区清理&#xff08;高频&#xff09;核心作用竞赛常用写法典型竞赛场景注意事项3. cin.getline() - 整行读取&#xff08;含空格&#xff0…

作者头像 李华
网站建设 2026/3/31 19:25:14

全网最全8个AI论文写作软件,MBA论文写作必备!

全网最全8个AI论文写作软件&#xff0c;MBA论文写作必备&#xff01; AI 工具如何改变论文写作的未来 在当今这个信息爆炸的时代&#xff0c;MBA 学生和研究人员面临着前所未有的挑战。无论是撰写高质量的论文&#xff0c;还是确保内容符合学术规范&#xff0c;都需要耗费大量…

作者头像 李华
网站建设 2026/3/13 21:43:22

一维、二维和多维列联表的应用场景与实例分析

下面内容摘录自《用R探索医药数据科学》专栏文章的部分内容&#xff08;原文5153字&#xff09;。 2篇4章1节&#xff1a;定性数据描述之列联表&#xff0c;文末有优势比计算介绍 一、一维列联表 二、二维和多维列联表 1、二维列联表 2、多维列联表 三、边际频数和边际比例…

作者头像 李华
网站建设 2026/3/23 2:03:31

LangChain使用

首先我们需要安装ollama&#xff0c;官方网站为&#xff1a;https://ollama.com/ 下载好了以后&#xff0c;我们需要下载deepseek模型&#xff0c;可以使用 ollama run deepseek-r1:1.5b 完成前面两部准备工作以后&#xff0c;我们就可以开启langchain的学习之路了。 本地大…

作者头像 李华
网站建设 2026/4/4 7:53:22

5款降AI率工具横评:嘎嘎降AI vs 比话降AI,谁更值得买

5款降AI率工具横评&#xff1a;嘎嘎降AI vs 比话降AI&#xff0c;谁更值得买 测了5款降AI率工具&#xff0c;花了差不多200块。结论出乎意料&#xff1a;最便宜的那个效果最好。 我的推荐排名&#xff1a;1. 嘎嘎降AI&#xff08;性价比之王&#xff09;2. 比话降AI&#xff…

作者头像 李华
网站建设 2026/3/27 8:33:26

基于python的京东评论数据分析可视化

前言   随着电子商务的快速发展&#xff0c;京东等电商平台上的商品评论数据日益丰富。这些评论数据不仅反映了消费者对商品的满意度&#xff0c;还蕴含着市场趋势、用户偏好等有价值的信息。然而&#xff0c;面对海量的评论数据&#xff0c;传统的人工分析方式效率低下&…

作者头像 李华