MyBatis 源码 学习一

Configuration: MyBatis在运行期的基本上所有的数据都会汇总到这个类。它的初始数据是来自开发人员配置在configuration的xml配置文件

MyBatis允许用户的自定义插件可以拦截ParameterHandler,ResultSetHandler,StatementHandler,Executor接口,从而进行一些操作。

SqlSessionFactoryBuilder类(入口) 里的build方法   中调用XMLConfigBuilder类的parse方法进行配置文件的读取。

SqlSessionFactoryBuilder类 入口代码: 创建SqlSessionFactory对象

 public SqlSessionFactory build(Reader reader, String environment, Properties properties) {

    try {

      XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);

      return build(parser.parse());

    } catch (Exception e) {

      throw ExceptionFactory.wrapException("Error building SqlSession.", e);

    } finally {

      ErrorContext.instance().reset();

      try {

        reader.close();

      } catch (IOException e) {

        // Intentionally ignore. Prefer previous error.

      }

    }

  }

  

 parser.parse()方法用于读取mapping中的配置文件内容。

 XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties); 构造方法中调用   super(new Configuration()); Configuration()构造方法 如下:

   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; 

  }

  

关键方法:SqlSession中的getMapper方法. 桥梁作用,通过java动态代理实现。。(SqlSession有一个重要的方法getMapper,顾名思义,这个方式是用来获取Mapper对象的。什么是Mapper对象?根据Mybatis的官方手册,应用程序除了要初始并启动Mybatis之外,还需要定义一些接口,接口里定义访问数据库的方法,存放接口的包路径下需要放置同名的XML配置文件。SqlSession的getMapper方法是联系应用程序和Mybatis纽带,应用程序访问getMapper时,Mybatis会根据传入的接口类型和对应的XML配置文件生成一个代理对象,这个代理对象就叫Mapper对象。应用程序获得Mapper对象后,就应该通过这个Mapper对象来访问Mybatis的SqlSession对象,这样就达到里插入到Mybatis流程的目的。)

  

  

  

  

  

猜你喜欢

转载自xinjiatao.iteye.com/blog/2212949