一、MyBatis的功能架构
我们把Mybatis的功能架构分为四层:
(1)API接口层:提供给外部使用的接口API,开发人员通过这些本地API来操纵数据库。接口层一接收到调用请求就会调用数据处理层来完成具体的数据处理。
(2)数据处理层:负责具体的SQL查找、SQL解析、SQL执行和执行结果映射处理等。它主要的目的是根据调用的请求完成一次数据库操作。
(3框架支撑层:负责最基础的功能支撑,包括连接管理、事务管理、配置加载和缓存处理,这些都是共用的东西,将他们抽取出来作为最基础的组件。为上层的数据处理层提供最基础的支撑。
(4)引导层:负责配置一些Mybatis运行环境,注册Sql映射文件
二、Mybatis的解析和运行原理
java代码:
String resource = "mybatis-config.xml";
Reader reader = Resources.getResourceAsReader(resource);
sessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sessionFactory.openSession();
EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
Employee employee = mapper.getEmpByIdWithDeptName(2);
首先先来解析前两行代码
String resource = "mybatis-config.xml";
Reader reader = Resources.getResourceAsReader(resource);
这两行代码的主要作用就是读取Mybaits的主配置配置文件,并返回该文件的输入流,我们知道Mybatis所有的SQL语句都写在XML配置文件里面,所以第一步就需要读取这些XML配置文件,这个不难理解,关键是读取文件后怎么存放。
(一)、构建SqlSessionFactory过程
SqlSessionFactory的主要功能是提供创建Mybatis的核心接口SqlSession,所以首先要创建SqlSessionFactory
构建SqlSessionFactory的代码
sessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSessionFactoryBuilder().build(reder)的具体实现:
public SqlSessionFactory build(Reader reader) {
return build(reader, null, null);
}
最终调用的是:
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
这里需要注意的是这两行代码:
进行解析配置文件和返回SqlSessionFactory
//创建一个配置文件流的解析对象XMLConfigBuilder,其实这里是将环境和配置文件流赋予解析类
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
// 解析类对配置文件进行解析并将解析的内容存放到Configuration对象中,并返回SqlSessionFactory
return build(parser.parse());
通过org.apache.ibatis.builder.xml.XMLConfigBuilderlai 的parse()方法来解析配置的XML文件,读取配置的参数
1、XMLConfigBuilder parser = new XMLCon