从 mybatis 的官网,写最简单的 “ HelloWorld ”
Reader reader = Resources.getResourceAsReader("conf.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = factory.openSession();
StudentDao mapper = session.getMapper(StudentDao.class);
System.err.println(mapper.listStudent());
首先解析全局配置文件, 转换成一个 Reader 对象, 这个是 JDK 的代码,直接看第二行, 创建了一个 SqlSessionFactory
对象
SqlSesseionFactory
使用了 建造者模式,, 最后调用的是 build 方法,创建了一个 SqlSessionFactory 对象
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
// 将全局配置文件转换成一个 Document 对象放入 XPathParser 对象中
// 而 XPathParser 对象保存在此 XMLConfiguration 对象中
// 这个 Document 对象类似于 “树” 结构
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
// 开始解析这个 Document 对象, 保存为一个 Configuration 对象中
// 创建默认的 SqlSessionFactory 对象, DefaultSqlSessionFactory
return build(parser.parse());
}
....
}
解析全局配置文件
// 由 XMLConfigBuilder 对象解析
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
// 解析完毕后设置一个标志位, 只能解析配置文件一次
parsed = true;
// 解析配置文件中的 <configuration> 标签, 保存到 XNode 对象中
// 然后处理这个 XNode 对象
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
解析 <configuration>
下的所有子标签
// 挨个解析所有子标签, 可以看到, 严格按照顺序依次执行
private void parseConfiguration(XNode root) {
try {
propertiesElement(root.evalNode("properties"));
// 将 <setting> 标签的元素保存为 properties 对象
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
// 日志
loadCustomLogImpl(settings);
typeAliasesElement(root.evalNode("typeAliases"));
pluginElement(root.evalNode("plugins"));
objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
reflectorFactoryElement(root.evalNode("reflectorFactory"));
settingsElement(settings);
// 解析并创建数据源
environmentsElement(root.evalNode