Mybatis工作原理
一、系统启动阶段
- 在
SqlSessionFactoryBean
中初始化sqlSessionFactoryBuilder
:
private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
- 在
afterPropertiesSet
方法中构建SqlSessionFactory
:
public void afterPropertiesSet() throws Exception {
......
this.sqlSessionFactory = this.buildSqlSessionFactory();
}
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
// Configuration对象的生成
......
return this.sqlSessionFactoryBuilder.build(configuration);
}
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
从上面的代码可以看出,SqlSessionFactory
仅仅是new DefaultSqlSessionFactory(config)
,所以其中最重要的还是Configuration
对象的生成。
Configuration 对象的生成:
(1)读取mybatis-config.xml,将mybatis的运行环境等信息(例如数据库连接信息)放到Configuration
对象中。
(2)读取mapper.xml,构建MappedStatement
对象放到Configuration
对象中。
mapper.xml文件中的一个<select | update | delete | insert>标签对应一个MappedStatement
对象,MappedStatement
对象封装了sql语句、参数、结果、sql类型(select|update|delete|insert)等信息。MappedStatement
的id是mapper接口全路径名+方法名。
MappedStatement
对象在Configuration
中以Map形式存在,key就是MappedStatement
对象的id,value是MappedStatement
对象:
protected final Map<String, MappedStatement> mappedStatements;
二、查询阶段
- 开启会话
调用DefaultSqlSessionFactory
中的openSession()
方法开启会话,获得SqlSession
对象。 SqlSession
对象根据mapper接口全路径名+方法名获取到MappedStatement
对象,将查询任务委托给执行器Executor
。- 执行器
Executor
主要负责维护一级缓存和二级缓存,并提供事务管理的相关操作,它会将数据库相关操作委托给StatementHandler
完成。 StatementHandler
使用PreparedStatement
对象去执行sql,并处理返回结果:
PreparedStatement ps = (PreparedStatement)statement;
ps.execute();
return this.resultSetHandler.handleResultSets(ps);