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)一次性执行,以提高性能。正确使用批处理可以在执行大量类似操作时大幅度减少应用与数据库的交互次数,优化应用性能。不过,要注意批处理可能会对事务管理、错误处理等方面带来额外的复杂性,使用时需要特别留意。

相关推荐
掘金者阿豪38 分钟前
🚀 CentOS Stream 9服务器Docker部署KWDB:从零到跨模查询实战全记录
后端
yang_xin_yu44 分钟前
一文带你精通泛型PECS原则与四大核心函数式接口
后端
孟陬1 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端
树獭叔叔1 小时前
13-KV Cache与位置编码表:大模型推理加速的核心技术
后端·aigc·openai
想用offer打牌1 小时前
一站式了解四种限流算法
java·后端·go
嘻哈baby1 小时前
用 C++ 写线程池是怎样一种体验?
后端
嘻哈baby1 小时前
SQL Server 和 Oracle 以及 MySQL 有哪些区别?
后端
绝无仅有1 小时前
Redis过期删除与内存淘汰策略详解
后端·面试·架构
武子康1 小时前
大数据-237 离线数仓 - Hive 广告业务实战:ODS→DWD 事件解析、广告明细与转化分析落地
大数据·后端·apache hive
绝无仅有1 小时前
Redis大Key问题排查与解决方案全解析
后端·面试·架构