Spring+Mybatis如何处理大批量sql(for循环+批处理法)

如果只是单纯地将Mapper语句放在循环中,那么会为每次的循环都创建一个事务,导致大批量的sql耗时会很长。

如果我们让在同一个循环中的Mapper语句在一个事务中提交,批处理这些sql,不多次创建事务,那么我们就能极大地改善大批量sql的执行时间了。

代码如下:

java 复制代码
import com.hbnu.mapper.TestMapper;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TestService {
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    public void BatchDoSql(){
        //关闭自动提交,开启事务,即开启批处理
        SqlSession sqlSession= sqlSessionFactory.openSession(ExecutorType.BATCH,false);
        //获取Mapper映射
        TestMapper mapper=sqlSession.getMapper(TestMapper.class);
        try{
            for(int i=0;i<50000;i++){
                String data="test";
                mapper.insert(data);
            }
            sqlSession.commit();//将sql一次性提交
        }catch (Exception e){
            sqlSession.rollback();//回滚
            throw e;
        }
        sqlSession.close();
    }
}
相关推荐
乌暮5 小时前
Spring AOP 与 Spring 事务:用大白话彻底理解原理与实践
java·数据库·spring boot·后端·sql·学习·spring
YDS8295 小时前
Small Spring IOC篇:容器事件及其监听器
java·spring
北漂人Java6 小时前
基于 Spring AI Alibaba WorkFlow 构建 Java 生产级 AI Agent
java·人工智能·spring
liangbo79 小时前
Spring系列11:切点表达式
java·spring
AllData公司负责人18 小时前
AI大模型数据开发底座系列说明书,AllData集成Chat2DB开源项目建设AI 数据库分析底座,涵盖AI 洞察/对话SQL/智能视图!
数据库·人工智能·sql·开源·ai 洞察·对话sql
budingxiaomoli1 天前
Spring统一功能处理
java·后端·spring
Decay__1 天前
SQLServer 索引与 SQL 优化 —— 聚集索引、非聚集索引、覆盖索引、碎片维护与执行计划
运维·数据库·sql·mysql·架构
阿达和自己1 天前
springboot学习-springboot引入MyBatis-Plus
spring boot·学习·mybatis
budingxiaomoli1 天前
Spring AOP
java·spring·java-ee
星恒随风2 天前
MySQL 从零入门(五):MySQL 内置函数详解——日期、字符串、数学函数与实战案例
linux·数据库·笔记·sql·mysql