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

相关推荐
brzhang1 分钟前
代码即图表:dbdiagram.io让数据库建模变得简单高效
前端·后端·架构
Jamesvalley6 分钟前
【Django】新增字段后兼容旧接口 This field is required
后端·python·django
秋野酱18 分钟前
基于 Spring Boot 的银行柜台管理系统设计与实现(源码+文档+部署讲解)
java·spring boot·后端
獨枭1 小时前
Spring Boot 连接 Microsoft SQL Server 实现登录验证
spring boot·后端·microsoft
shanzhizi1 小时前
springboot入门-controller层
java·spring boot·后端
电商api接口开发2 小时前
ASP.NET MVC 入门指南三
后端·asp.net·mvc
声声codeGrandMaster2 小时前
django之账号管理功能
数据库·后端·python·django
我的golang之路果然有问题2 小时前
案例速成GO+redis 个人笔记
经验分享·redis·笔记·后端·学习·golang·go
嘻嘻嘻嘻嘻嘻ys3 小时前
《Vue 3.3响应式革新与TypeScript高效开发实战指南》
前端·后端
暮乘白帝过重山3 小时前
路由逻辑由 Exchange 和 Binding(绑定) 决定” 的含义
开发语言·后端·中间件·路由流程