-
执行流程
步骤:
1、加载配置文件到Configuration
2、构建SqlSessionFactory
3、打开SqlSession会话
4、Executor开始处理请求
5、SqlSource解析SQL语句
6、StatementHandler执行SQL语句
7、ParameterHandler设置参数
8、StatementHandler执行SQL语句
9、ResultSetHandler处理结果集
源码解析
Configuration类,框架的核心配置类保存了包括映射器、别名、映射方法等信息
//Mapper接口+XML保存在这 protected final MapperRegistry mapperRegistry = new MapperRegistry(this); protected final InterceptorChain interceptorChain = new InterceptorChain(); //类型处理器都在这里 protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry(); //类型别名都保存在这 protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry(); protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry(); //所有的增删改查(SQL语句)都保存在个Map中 protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection")
SqlSessionFactoryBuilder.build()
通过build方法对配置文件进行解析并初始化,通过源码可知build方法有很多重载
public SqlSessionFactory build(Configuration config) { //SqlSession的工厂 return new DefaultSqlSessionFactory(config); }
XMLConfigBuilder,解析核心配置
Mybatis缓存
一级缓存:为SqlSession级别的缓存,默认开启
二级缓存:为Mapper级别,第一次调用mapper下的SQL去查询用户的信息,查询到的信息会存放代该mapper对应的二级缓存区域。 第二次调用namespace下的mapper映射文件中,相同的sql去查询用户信息,会去对应的二级缓存内取结果。默认是不开启二级缓存的,可以在配置文件中开启。
<settings> //开启二级缓存 <setting name="cacheEnabled" value="true"/> </settings>