1. MyBatis执行SQL流程概览
在Java持久层框架中,MyBatis以其灵活性和高性能著称。理解其SQL执行机制对于开发高效、稳定的数据访问层至关重要。让我们从一个典型的使用场景开始:
java复制public class MyBatisDemo {
public static void main(String[] args) throws IOException {
// 1. 读取配置文件
String resource = "mybatis-config.xml";
Reader reader = Resources.getResourceAsReader(resource);
// 2. 构建SqlSessionFactory
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(reader);
// 3. 获取SqlSession
SqlSession session = sqlSessionFactory.openSession();
try {
// 4. 获取Mapper代理对象
UserMapper mapper = session.getMapper(UserMapper.class);
// 5. 执行SQL
User user = mapper.selectById(11);
System.out.println(user.getUserName());
} finally {
// 6. 关闭会话
session.close();
}
}
}
这段代码展示了MyBatis的六个核心步骤。本文将重点剖析步骤3-5的执行细节,揭示从SqlSession创建到最终JDBC Statement执行的完整过程。
提示:在实际项目中,建议使用Spring集成MyBatis,这样可以省去手动管理SqlSession的繁琐操作,但底层执行原理保持不变。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. SqlSession创建过程:openSession()详解
2.1 openSession()的调用链
SqlSessionFactory是创建SqlSession的工厂接口,其核心实现是DefaultSqlSessionFactory:
java复制public interface SqlSessionFactory {
SqlSession openSession();
SqlSession openSession(boolean autoCommit);
SqlSession openSession(ExecutorType execType);
// 其他重载方法...
}
public class DefaultSqlSessionFactory implements SqlSessionFactory {
@Override
public SqlSession openSession() {
return openSessionFromDataSource(
configuration.getDefaultExecutorType(),
null,
false
);
}
private SqlSession openSessionFromDataSource(
ExecutorType execType,
TransactionIsolationLevel level,
boolean autoCommit) {
Transaction tx = null;
try {
// 获取环境配置
final Environment environment = configuration.getEnvironment();
// 创建事务
final TransactionFactory transactionFactory =
getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(
environment.getDataSource(),
level,
autoCommit
);
// 创建执行器(核心)
final Executor executor = configuration.newExecutor(tx, execType);
// 创建DefaultSqlSession
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx);
throw ExceptionFactory.wrapException(
"Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
}
2.2 Executor的创建与包装
Executor是MyBatis执行SQL的核心组件,Configuration类的newExecutor方法负责创建:
java复制public class Configuration {
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
// 确定执行器类型
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
// 根据类型创建基础执行器
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
// 如果开启二级缓存,包装为CachingExecutor
if (cacheEnabled) {
executor =
