Mybatis跟踪源码的那些事(二)

1.我们先看下程序入口

public static void main(String[] args) {
    
    try {
     //核心配置文件 String resource
= "configuration.xml";
     //将文件写入流 InputStream inputStream
= Resources.getResourceAsStream(resource);
     //我们跟进下build() SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); SysUserMapper mapper = sqlSession.getMapper(SysUserMapper.class); List<SysUser> list = mapper.getAll(); System.out.println(list); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

SqlSessionFactoryBuilder

  public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
    //XMLConfigBuilder 读取配置文件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. } } }

跟进parse()方法

  public Configuration parse() {
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true;
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
  }

跟进parseConfiguration方法,解析配置,传入的参数就是我们xml配置文件的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"));
      environmentsElement(root.evalNode("environments")); // read it after objectFactory and objectWrapperFactory issue #631
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      typeHandlerElement(root.evalNode("typeHandlers"));
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }
原文地址:https://www.cnblogs.com/liudingwei/p/14744979.html