/ 支持不同参数组合 <T> T selectOne(String statement); <T> T selectOne(String statement, Object parameter); <E> List<E> selectList(String statement, Object parameter); <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds);优势:
- 使用灵活:支持不同使用场景
- 向后兼容:保持API的向后兼容性
- 渐进式学习:从简单到复杂的使用方式
2.2.4 资源管理设计
public interface SqlSession extends Closeable { // 继承Closeable接口,支持try-with-resources语法 }优势:
- 自动资源管理:支持try-with-resources语法
- 防止资源泄漏:确保资源正确释放
- 代码简洁:减少样板代码
3. SqlSessionFactory工厂模式分析
3.1 SqlSessionFactory接口设计
SqlSessionFactory是创建SqlSession的工厂接口,采用工厂模式设计:
package org.apache.ibatis.session; import java.sql.Connection; public interface SqlSessionFactory { // 基本创建方法 SqlSession openSession(); SqlSession openSession(boolean autoCommit); SqlSession openSession(Connection connection); // 执行器类型指定 SqlSession openSession(ExecutorType execType); SqlSession openSession(ExecutorType execType, boolean autoCommit); SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level); SqlSession openSession(ExecutorType execType, Connection connection); // 事务隔离级别指定 SqlSession openSession(TransactionIsolationLevel level); // 配置获取 Configuration getConfiguration(); }3.2 DefaultSqlSessionFactory实现分析
DefaultSqlSessionFactory是SqlSessionFactory的默认实现,让我们深入分析其源码:
package org.apache.ibatis.session.defaults; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.TransactionIsolationLevel; import org.apache.ibatis.transaction.Transaction; import org.apache.ibatis.transaction.TransactionFactory; import org.apache.ibatis.transaction.managed.ManagedTransactionFactory; import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.exceptions.ExceptionFactory; import org.apache.ibatis.executor.ErrorContext; public class DefaultSqlSessionFactory implements SqlSessionFactory { private final Configuration configuration; public DefaultSqlSessionFactory(Configuration configuration) { this.configuration = configuration; } @Override public SqlSession openSession() { return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false); } @Override public SqlSession openSession(boolean autoCommit) { return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, autoCommit); } @Override public SqlSession openSession(ExecutorType execType) { return openSessionFromDataSource(execType, null, false); } // 核心创建方法 private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) { Transaction tx = null; try { // 1. 获取环境配置 final Environment environment = configuration.getEnvironment(); // 2. 获取事务工厂 final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment); // 3. 创建事务 tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit); // 4. 创建执行器 final Executor executor = configuration.newExecutor(tx, execType); // 5. 创建SqlSession return createSqlSession(configuration, executor, autoCommit); } catch (Exception e) { closeTransaction(tx); throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } } protected SqlSession createSqlSession(Configuration configuration, Executor executor, boolean autoCommit) { return new DefaultSqlSession(configuration, executor, autoCommit); } }3.3 工厂模式的优势
3.3.1 封装复杂性
// 用户只需要调用简单的方法 SqlSession session = sqlSessionFactory.openSession(); // 内部复杂的创建过程被封装 // 1. 环境配置获取 // 2. 事务工厂创建 // 3. 事务对象创建 // 4. 执行器创建 // 5. SqlSession创建3.3.2 参数灵活性
// 支持多种参数组合 SqlSession session1 = sqlSessionFactory.openSession(); // 默认配置 SqlSession session2 = sqlSessionFactory.openSession(true); // 自动提交 SqlSession session3 = sqlSessionFactory.openSession(ExecutorType.BATCH); // 批处理执行器3.3.3 配置驱动
// 基于Configuration配置创建SqlSession final Executor executor = configuration.newExecutor(tx, execType);4. SqlSession生命周期管理
4.1 生命周期阶段
SqlSession的生命周期可以分为以下几个阶段:
openSession
commit/rollback
close
Environment
Transaction
Executor
select/update
getMapper
操作完成
结束事务
executor.close
tx.close
clearCache
🔄 创建阶段
⚡ 使用阶段
🔒 事务管理阶段
🧹 资源释放阶段
📋 获取配置
🏗️ 创建事务
⚙️ 创建执行器
🎯 创建SqlSession
💾 执行SQL
📊 结果处理
🔗 Mapper调用
🚀 事务开始
✅ 提交/回滚
🏁 事务结束
🔧 关闭执行器
🔐 关闭事务
🔌 关闭连接
🗑️ 清理缓存
4.2 创建阶段详细分析
4.2.1 配置获取
// 从Configuration获取环境配置 final Environment environment = configuration.getEnvironment();Environment包含:
- DataSource:数据源配置
- TransactionFactory:事务工厂配置
- Id:环境标识
4.2.2 事务创建
// 创建事务对象 final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment); tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);事务创建过程:
- 获取事务工厂:从环境配置获取TransactionFactory
- 创建事务对象:使用DataSource和参数创建Transaction
- 设置事务属性:隔离级别、自动提交等
4.2.3 执行器创建
// 创建执行器 final Executor executor = configuration.newExecutor(tx, execType);执行器创建过程:
- 执行器类型选择:根据ExecutorType选择具体实现
- 缓存包装:如果启用缓存,用CachingExecutor包装
- 插件应用:应用所有配置的插件
4.2.4 SqlSession创建
// 创建SqlSession对象 return new DefaultSqlSession(configuration, executor, autoCommit);4.3 使用阶段分析
4.3.1 SQL执行流程
// 用户调用 User user = session.selectOne("selectUser", 1); // 内部执行流程 public <T> T selectOne(String statement, Object parameter) { List<T> list = this.selectList(statement, parameter); if (list.size() == 1) { return list.get(0); } if (list.size() > 1) { throw new TooManyResultsException("Expected one result..."); } else { return null; } }4.3.2 Mapper获取流程
// 用户调用 UserMapper mapper = session.getMapper(UserMapper.class); // 内部实现 @Override public <T> T getMapper(Class<T> type) { return configuration.getMapper(type, this); }4.4 资源释放阶段
4.4.1 手动关闭
// 手动关闭SqlSession session.close(); // 内部关闭流程 @Override public void close() { try { executor.close(isCommitOrRollbackRequired(false)); } catch (SQLException e) { throw ExceptionFactory.wrapException("Error closing SqlSession. Cause: " + e, e); } finally { // 清理资源 dirty = false; executor = null; configuration = null; } }