1.我们先从Mybatis 的入口开始解读(单独版,没有与spring整合)
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sessionFactory.openSession();
List<Country> list = sqlSession.selectList("selectAll");
/*CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
List<Country> list = mapper.selectAll();*/
list.forEach(country -> {
String countryname = country.getCountryname();
System.out.println(countryname);
});
第一行代码,通过Reader对象读取配置文件转成流
第二行代码,从表面上看,我们知道通过SqlSessionFactoryBuilder 对象使用builder方法构建生成了SqlSessionFactory对象
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
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 SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
从源码我们也知道最后面也通过构造器生成的SqlSessionFactory对象
但是在这中间的过程Mybatis 读取配置文件做了那些的事情
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment,properties);
我们首先先解读下第一个方法,是通过构造器,实例化XMLConfigBuilder 对象
我们可以先看看这个对象里面的属性有什么
class XMLConfigBuilder
属性
private boolean parsed; private final XPathParser parser; private String environment; private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();
class XPathParser 属性 private final Document document; //文档,用于处理html/xml 文件格式数据,封装数据 private boolean validation; private EntityResolver entityResolver; //用于处理sts 文件 private Properties variables; private XPath xpath; //用于解析XML文档
public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {
this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);
}
private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
super(new Configuration());
ErrorContext.instance().resource("SQL Mapper Configuration");
this.configuration.setVariables(props);
this.parsed = false;
this.environment = environment;
this.parser = parser;
}
初始化了Configuration对象,并对器初始化了基础值