mybatis源码专题(一)
1)SqlSessionFactory是什么
SqlSessionFactory是MyBatis的关键对象,它是单个数据库映射关系经过编译后的内存镜像
2)如何创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("classpath:mybatis-config.xml"));
3)核心流程
1、Resources构建mybatis-config.xml数据流
public static Reader getResourceAsReader(String resource) throws IOException {
InputStreamReader reader;
if (charset == null) {
reader = new InputStreamReader(getResourceAsStream(resource));
} else {
reader = new InputStreamReader(getResourceAsStream(resource), charset);
}
return reader;
}
2、XMLConfigBuilder将config.xml数据流解析并封装返回Configuration对象
public Configuration parse() {
if (this.parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
} else {
this.parsed = true;
this.parseConfiguration(this.parser.evalNode("/configuration"));
return this.configuration;
}
}
3、将Configuration对象交给SqlSessionFactoryBuilder构建SqlSessionFactory
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
4)SqlSessionFactory对象创建的分析
5)总结
SqlSessionFactory创建的过程:项目中配置的config.xml,mapper.xml这两个xml文件,分别由XmlConfigBuilder,XmlMapperBuilder解析并封装成相应的节点对象,组合成Configuration对象交到SqlSessionFactoryBuilder手中,然后通过SqlSessionFactoryBuilder调用其build(Configuration config) 函数返回一个SqlSessionFactory接口的实例对象DefaultSqlSessionFactory