请求流程
一、通过 DefaultSqlSessionFactory 生成 SqlSession
关键代码
DefaultSqlSessionFactory.class
- 关键方法
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);
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx);
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
代码分析
- 要创建 SqlSession 对象,需要三个参数:configuration, executor, autoCommit
- configuration 配置信息,主要包含以下属性
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/88345dea70a832166b66171dd8bd29a8.png)
- mappedStatements:
- 每个 Dao 方法有两个 mappedStatement
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ef494286c6bfcf9590b3ba092e6779eb.png)
- mappedStatement 的属性值:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/45b5b05937a949f0a230ef9b7a42f76f.png)
- resource :生成这个 mappedStatement 的资源文件
- file [D:\项目路径\user_mapper.xml]
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5968bfb38ac060baaf56f07b1ee0571d.png)
- id:和方法对应
- awesome.user.server.dao.UserDao.getUserById
- statementType:statement 类型
- sqlSource:和方法对应
- resultMaps:每个 resultMap 描述了数据库字段和类属性的映射关系
- sqlCommandType:SQL 命令类型
- resultMaps:每个 resultMap 描述了数据库字段和类属性的映射关系
- loadedResources:加载的资源
二、SqlSessionTemplate 中以 SqlSession 作为参数进行反射调用
关键代码:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
SqlSession sqlSession = SqlSessionUtils.getSqlSession(SqlSessionTemplate.this.sqlSessionFactory, SqlSessionTemplate.this.executorType, SqlSessionTemplate.this.exceptionTranslator);
Object unwrapped;
try {
Object result = method.invoke(sqlSession, args);
if (!SqlSessionUtils.isSqlSessionTransactional(sqlSession