mybatis-plus批量插入生效条件和源码分析


mybatis-plus批量插入生效条件和源码分析

代码

com.baomidou.mybatisplus.extension.service.IService#saveBatch(java.util.Collection<T>)

源码实现




可以看到使用的是ExecutorType.BATCH执行器

mybatis中BATCH执行器源码


如图可以看到使用的是JDBC底层的addBatch方法,最后flush中调用executeBatch真正开始执行

JDBC层(mysql-connector-java:8)

protected long[] executeBatchInternal() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if (this.connection.isReadOnly()) {
                throw new SQLException(Messages.getString("PreparedStatement.25") + Messages.getString("PreparedStatement.26"),
                        MysqlErrorNumbers.SQL_STATE_ILLEGAL_ARGUMENT);
            }
            if (this.query.getBatchedArgs() == null || this.query.getBatchedArgs().size() == 0) {
                return new long[0];
            }

            // we timeout the entire batch, not individual statements
            int batchTimeout = getTimeoutInMillis();
            setTimeoutInMillis(0);
            resetCancelledState();

            try {
                statementBegins();
                clearWarnings();
                //batch不包含sql字符串,并且开启rewriteBatchedStatements
                if (!this.batchHasPlainStatements && this.rewriteBatchedStatements.getValue()) {
                    //判断是否可以改写为mutil-value insert
                    if (((PreparedQuery<?>) this.query).getParseInfo().canRewriteAsMultiValueInsertAtSqlLevel()) {
                        return executeBatchedInserts(batchTimeout);
                    }
                    //batch数量大于3,通过multi statement执行sql
                    if (!this.batchHasPlainStatements && this.query.getBatchedArgs() != null
                            && this.query.getBatchedArgs().size() > 3 /* cost of option setting rt-wise */) {
                        return executePreparedBatchAsMultiStatement(batchTimeout);
                    }
                }
                //顺序执行
                return executeBatchSerially(batchTimeout);
            } finally {
                this.query.getStatementExecuting().set(false);

                clearBatch();
            }
        }
    }

如上代码注释批量执行的基本条件要开启rewriteBatchedStatements并且没有plain sql


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM