如何批量插入10万条数据的思路

在进行批量插入时,通常有两种主要的思路:
使用for循环逐条插入(需要开启批处理):
生成一条SQL语句进行插入:
关键是要评估网络IO所需的时间是否超过SQL插入的时间,这是选择批量插入方法的核心问题。
根据实际情况选择合适的批量插入方法。
MyBatis Plus的批量插入方法
MyBatis Plus提供了一个批量插入方法saveBatch,我们来看一下它的实现源码:
@Transactional(rollbackFor = Exception.class)
@Override
public boolean saveBatch(Collection<T> entityList, int batchSize) {
String sqlStatement = getSqlStatement(SqlMethod.INSERT_ONE);
return executeBatch(entityList, batchSize, (sqlSession, entity) -> sqlSession.insert(sqlStatement, entity));
}这里的sqlStatement是INSERT_ONE,即逐条插入。
executeBatch方法如下:
public static <E> boolean executeBatch(Class<?> entityClass, Log log, Collection<E> list, int batchSize, BiConsumer<SqlSession, E> consumer) {
Assert.isFalse(batchSize < 1, "batchSize must not be less than 1");
return SqlSessionUtils.doBatch(entityClass, log, list, batchSize, (sqlSession, entityList) -> {
int size = list.size();
int i = 1;
for (E element : list) {
consumer.accept(sqlSession, element);
if ((i % batchSize == 0) || i == size) {
sqlSession.flushStatements();
}
i++;
}
});
}注意return中的第三个参数是一个lambda表达式,这是MP批量插入的核心逻辑。MP首先对数据进行分片(默认分片大小为1000),然后逐条插入。进一步查看executeBatch方法,会发现这里的sqlSession实际上是一个批处理的sqlSession,而不是普通的sqlSession。
参考资料
10万条数据批量插入,到底怎么做才快?分享计划
博客内容将同步至PHP中文网+社区,邀请大家一同入驻:https://www.php.cn/link/f7e88f8ae3ce74bc6225e0b5c78a46b8
许可协议
本文采用 署名-非商业性使用-相同方式共享 4.0 国际 许可协议,转载请注明出处。
以上就是如何批量插入10万条数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号