本文主要介绍mybaits的核心执行过程的源码分析,我们按照xml配置的方式,建立一个查询的demo,测试代码如下
@Test
public void test2() throws Exception {
InputStream in = Resources.getResourceAsStream("custom/sqlMapConfig2.xml");
SqlSessionFactory factory2 = new SqlSessionFactoryBuilder().build(in);
SqlSession openSession = factory2.openSession();
UserMapper mapper = openSession.getMapper(UserMapper.class);
User user = mapper.findUserById(1);
// User user = openSession.selectOne("com.wj.source_two.demo.mapper.UserMapper.findUserById", 1);
System.out.println(user);
openSession.close();
}
按照上面的代码执行过程,我们把执行过程分为下面几个部分分析: 配置加载,创建mapper代理,SqlSession执行
一、配置加载
1、相关的类
SqlSessionFactoryBuilder : 负责创建SqlSessionFactory对象,并且传入了从配置文件解析的Configuration。
XMLConfigBuilder: 核心解析类及其父类BaseBuilder的子类,负责解析xml各种配置到Configuration对象。
XPathParser:xpath解析
XNode:node的包装
2、流程分析
1) SqlSessionFactoryBuilder调用XMLConfigBuilder解析输入流解析到Configuration
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
return build(parser.parse());
2) parse方法是对sqlMapConfig.xml的解析,XPathParser和XNode用法后期补充。
public Configuration parse() {
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
private void parseConfiguration(XNode root) {
try {
propertiesElement(root.evalNode("properties")); //issue #117 read properties first
typeAliasesElement(root.evalNode("typeAliases"));
pluginElement(root.evalNode("plugins"));
objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
settingsElement(root.evalNode("settings"));