Mybatis可以说是Java开发在实际中用到的最多的ORM框架了。我们只需要引入Mybatis,配置好mybatis-config.xml文件,在实际开发的时候,写一个接口dao层,再写一个对应的xml文件,就可以了。最最主要的是上手真的很简单方便,相比于hibernate而言,学习成本要低很多。
既然是用的最多的,那么对于它的相关工作流程以及原理我们肯定是需要掌握的,要知其所以然,刨根问底才是一个好的程序员应有的品质。
一、工作流程
1.开始
@Test
public void MybatisTest() throws IOException {
String resource = "mybatis-config.xml";
//获取mybatis配置文件的IO流
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
DailyReportDao mapper = sqlSession.getMapper(DailyReportDao.class);
mapper.findList(null);
}
1.1创建SqlSessionFactory
SqlSessionFactory的创建是非常重要的,因为对于配置文件的加载、xml与dao层关联创建出代理对象都是在这里完成的,让我们往下追代码:
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
//创建出一个解析对象,重点看parser.parse()方法
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
inputStream.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
//mybatis-config.xml总是从<configuratin> . . .</configuration>开始的
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
继续进入到parseConfiguration(parser.evalNode("/configuration"));方法,该方法就是解析出我们的各个配置,像properties、settings这种我们可以不关注,但是mappers我们是要关注的,继续看
private void parseConfiguration(XNode root) {
try {
//将mybatis-config.xml中的各个配置set到Configuration对象实例中去
propertiesElement(root.evalNode("properties"));
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
typeAliasesElement(root.evalNode("typeAliases"));
pluginElement(root.evalNode("plugins"));
objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
reflectorFactoryElement(root.evalNode("reflectorFactory"));
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
environmentsElement(root.evalNode("environments"));
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
typeHandlerElement(root.evalNode("typeHandlers"));
//看这里,mappers是我们配置的包扫描路径
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
我们在配置mapper.xml的路径有几种方式:
- 使用相对于类路径的资源引用
<mappers>
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
<mapper resource="org/mybatis/builder/BlogMapper.xml"/>
<mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
- 使用完全限定资源定位符(URL) </