MyBatis(11)MyBatis 如何执行批处理操作

在MyBatis中,批处理操作是一种高效执行多条语句的方式,特别是当你需要在一个事务中插入、更新或删除多条记录时。批处理可以显著减少与数据库的交互次数,从而提高性能。

执行批处理的基本步骤

  1. 开启批处理模式 :在获取SqlSession时,需要指定执行器(Executor)类型为ExecutorType.BATCH
  2. 执行SQL语句:执行需要批处理的SQL语句,此时语句并不会立即执行,而是被添加到批处理队列中。
  3. 提交事务 :调用SqlSession.commit()方法,此时MyBatis会将批处理队列中的语句一次性发送给数据库执行。
  4. 处理批处理结果:提交事务后,可以通过批处理结果进行后续处理。

示例代码

java 复制代码
try (SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH)) {
    YourMapper mapper = sqlSession.getMapper(YourMapper.class);
    for (YourData data : dataList) {
        // 根据需要调用insert, update或delete方法
        mapper.insertOrUpdate(data);
    }
    sqlSession.commit();
    // 可以获取批处理结果,处理特定逻辑
}

深入源码解析

在MyBatis中,批处理的核心是BatchExecutor,这是Executor的一个实现。在开启批处理模式时,MyBatis会使用BatchExecutor来处理SQL会话。

BatchExecutor的关键方法

  • doUpdate : 当执行insert、update、delete方法时,BatchExecutor会将这些操作存储在内部的批处理队列中,而不是立即执行它们。

  • doFlushStatements : 当调用commitflushStatements时,BatchExecutor会执行批处理队列中的所有SQL语句。这些操作是通过JDBC的PreparedStatement.executeBatch()方法执行的。

java 复制代码
@Override
public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
    final Configuration configuration = ms.getConfiguration();
    final StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);
    final BoundSql boundSql = handler.getBoundSql();
    final String sql = boundSql.getSql();
    final Statement stmt;
    if (sql.equals(currentSql) && ms.equals(currentStatement)) {
        int last = statementList.size() - 1;
        stmt = statementList.get(last);
        applyTransactionTimeout(stmt);
        handler.parameterize(stmt);//fix Issues 322
    } else {
        Connection connection = getConnection(ms.getStatementLog());
        stmt = handler.prepare(connection, transaction.getTimeout());
        handler.parameterize(stmt);    //fix Issues 322
        currentSql = sql;
        currentStatement = ms;
        statementList.add(stmt);
        batchResultList.add(new BatchResult(ms, sql, parameter));
    }
    handler.batch(stmt);
    return BATCH_UPDATE_RETURN_VALUE;
}

执行批处理

当调用commitflushStatements时,BatchExecutor.doFlushStatements会被触发,它负责实际执行批处理操作。

java 复制代码
@Override
public List<BatchResult> doFlushStatements(boolean isRollback) throws SQLException {
    try {
        if (isRollback) {
            return Collections.emptyList();
        }

        List<BatchResult> results = new ArrayList<>();
        if (statementList.size() > 0) {
            for (int i = 0, n = statementList.size(); i < n; i++) {
                Statement stmt = statementList.get(i);
                BatchResult batchResult = batchResultList.get(i);
                try {
                    batchResult.setUpdateCounts(stmt.executeBatch());
                    MappedStatement ms = batchResult.getMappedStatement();
                    List<Object> parameterObjects = batchResult.getParameterObjects();
                    KeyGenerator keyGenerator = ms.getKeyGenerator();
                    if (Jdbc3KeyGenerator.class.equals(keyGenerator.getClass())) {
                        Jdbc3KeyGenerator jdbc3KeyGenerator = (Jdbc3KeyGenerator) keyGenerator;
                        jdbc3KeyGenerator.processBatch(ms, stmt, parameterObjects);
                    } else if (!NoKeyGenerator.class.equals(keyGenerator.getClass())) { //issue #141
                        for (Object parameter : parameterObjects) {
                            keyGenerator.processAfter(this, ms, stmt, parameter);
                        }
                    }
                } finally {
                    closeStatement(stmt);
                }
            }
        }
        return results;
    } finally {
        for (Statement stmt : statementList) {
            closeStatement(stmt);
        }
        currentSql = null;
        statementList.clear();
        batchResultList.clear();
    }
}

小结

MyBatis的批处理通过BatchExecutor实现,它通过将SQL语句收集到批处理队列中,然后在适当的时候(如调用commit)一次性执行,以提高性能。正确使用批处理可以在执行大量类似操作时大幅度减少应用与数据库的交互次数,优化应用性能。不过,要注意批处理可能会对事务管理、错误处理等方面带来额外的复杂性,使用时需要特别留意。

相关推荐
写bug写bug2 小时前
11个提高生产力的Go小技巧
后端·go
markix2 小时前
springboot 配置加密,jasypt加解密命令
java·spring boot·后端·jasypt
nbplus_0072 小时前
golang go-bindata打包配置文件嵌入到二进制文件
开发语言·后端·golang·个人开发·go配置文件
努力的小雨3 小时前
解码技术债:AI代码助手与智能体的革新之道
后端·aigc
LiamHong_3 小时前
简单了解 HTTP 请求方法
前端·后端·http·学习方法·web
Lucifer三思而后行3 小时前
Centos 7.9 一键安装 Oracle 12CR2 单机
后端·oracle
Flying_Fish_roe3 小时前
spring-08
java·后端·spring
爱分享的码瑞哥3 小时前
Rust 基础教程
开发语言·后端·rust
辣码甄源3 小时前
“让爷看看”!开源智能坐姿守护者:PoseMonitor
后端·开源·github
LightOfNight4 小时前
【后端面试题】【中间件】【NoSQL】ElasticSearch的优化方案2(减少字段、冷热分离、参数优化)
分布式·后端·elasticsearch·中间件·架构·nosql