【Mybatis】源码分析-深入源码

1、架构原理

1.1、架构设计

        我们把Mybatis的功能架构分为三层:

(1)、 API接⼝层:提供给外部使⽤的接口 API,开发⼈员通过这些本地API来操纵数据库。接⼝层⼀接收到调⽤请求就会调⽤数据处理层来完成具体的数据处理。

        MyBatis和数据库的交互有两种⽅式:

a、使⽤传统的MyBati s提供的API ;

b、 使⽤Mapper代理的⽅式

(2) 、数据处理层:负责具体的SQL查找、SQL解析、SQL执⾏和执⾏结果映射处理等。它主要的⽬的是根据调⽤的请求完成⼀次数据库操作。

(3) 、基础⽀撑层:负责最基础的功能⽀撑,包括连接管理、事务管理、配置加载和缓存处理,这些都是共⽤的东⻄,将他们抽取出来作为最基础的组件。为上层的数据处理层提供最基础的⽀撑。

1.2、主要构件及其相互关系

构件 描述
SqlSession 作为MyBatis⼯作的主要顶层API,表示和数据库交互的会话,完成必要数据库增删改查功能
Executor MyBatis执⾏器,是MyBatis调度的核⼼,负责SQL语句的⽣成和查询缓存的维护
StatementHandler 封装了JDBC Statement操作,负责对JDBC statement的操作,如设置参数、将Statement结果集转换成List集合。
ParameterHandler 负责对⽤户传递的参数转换成JDBC Statement所需要的参数,
ResultSetHandler 负责将JDBC返回的ResultSet结果集对象转换成List类型的集合;
TypeHandler 负责java数据类型和jdbc数据类型之间的映射和转换
MappedStatement MappedStatement维护了⼀条<select | update | delete | insert> 节点的封装
SqlSource 负责根据⽤户传递的parameterObject,动态地⽣成SQL语句,将信息封装到BoundSql对象中,并返回
BoundSql 表示动态⽣成的SQL语句以及相应的参数信息

1.3、总体流程

1.3.1、加载配置并初始化

触发条件:加载配置⽂件

        配置来源于两个地⽅,⼀个是配置⽂件(主配置⽂件conf.xml,mapper⽂件*.xml),—个是java代码中的注解,将主配置⽂件内容解析封装到Configuration,将sql的配置信息加载成为⼀个mappedstatement对象,存储在内存之中。

1.3.2、接收调用请求

触发条件:调⽤Mybatis提供的API

传⼊参数:为SQL的ID和传⼊参数对象

处理过程:将请求传递给下层的请求处理层进⾏处理。

1.3.3、处理操作请求

触发条件:API接⼝层传递请求过来

传⼊参数:为SQL的ID和传⼊参数对象

处理过程:

(A) 根据SQL的ID查找对应的MappedStatement对象。

(B) 根据传⼊参数对象解析MappedStatement对象,得到最终要执⾏的SQL和执⾏传⼊参数。

(C) 获取数据库连接,根据得到的最终SQL语句和执⾏传⼊参数到数据库执⾏,并得到执⾏结果。

(D) 根据MappedStatement对象中的结果映射配置对得到的执⾏结果进⾏转换处理,并得到最终的处理结果。

(E) 释放连接资源。

1.3.4、返回处理结果

        将最终的处理结果返回。

2、源码剖析

2.1、传统方式源码剖析

2.1.1、初始化

 //1.Resources工具类,配置文件的加载,把配置文件加载成字节输入流
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");

//2.解析了配置文件,并创建了sqlSessionFactory工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

进入源码分析:

 //1、外层调用的解析方法
public SqlSessionFactory build(InputStream inputStream) {
   //调用重载方法
   return build(inputStream, null, null);
 }

//2、重载方法
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
      // XMLConfigBuilder是专⻔解析mybatis的配置⽂件的类
      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
      
      //这⾥⼜调⽤了⼀个重载⽅法。parser.parse()的返回值是Configuration对象
      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.
      }
    }
  }

//3、构建工厂对象
public SqlSessionFactory build(Configuration config) {
    return new DefaultSqlSessionFactory(config);
  }

        MyBatis在初始化的时候,会将MyBatis的配置信息全部加载到内存中,使⽤ org.apache.ibatis.session.Configuration 实例来维护。下⾯进⼊对配置⽂件解析部分:

关于Configuration对象:

        Configuration对象的结构和xml配置⽂件的对象⼏乎相同。回顾⼀下xml中的配置标签有哪些:

        properties (属性),settings (设置),typeAliases (类型别名),typeHandlers (类型处理器),objectFactory (对象⼯⼚),mappers (映射器)等 Configuration也有对应的对象属性来封装它们。也就是说,初始化配置⽂件信息的本质就是创建Configuration对象,将解析的xml数据封装到Configuration内部属性中。

//解析 XML 成 Configuration 对象。
public Configuration parse() {
    //若已解析,抛出BuilderException异常
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    //标记已解析
    parsed = true;
    // 解析 XML configuration 节点
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
  }

//解析XML
private void parseConfiguration(XNode root) {
    try {
      //issue #117 read properties first
      // 解析 <properties /> 标签
      propertiesElement(root.evalNode("properties"));

      // 解析〈settings /> 标签
      Properties settings = settingsAsProperties(root.evalNode("settings"));

      //加载⾃定义的VFS实现类
      loadCustomVfs(settings);

      // 解析 <typeAliases /> 标签
      typeAliasesElement(root.evalNode("typeAliases"));

      //解析<plugins />标签
      pluginElement(root.evalNode("plugins"));

      // 解析 <objectFactory /> 标签
      objectFactoryElement(root.evalNode("objectFactory"));

      // 解析 <objectWrapperFactory /> 标签
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));

      // 解析 <reflectorFactory /> 标签
      reflectorFactoryElement(root.evalNode("reflectorFactory"));

      // 赋值 <settings /> ⾄ Configuration 属性
      settingsElement(settings);

      // read it after objectFactory and objectWrapperFactory issue #631
      // 解析〈environments /> 标签
      environmentsElement(root.evalNode("environments"));

      // 解析 <databaseIdProvider /> 标签
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));

      // 解析 <typeHandlers /> 标签
      typeHandlerElement(root.evalNode("typeHandlers"));

      //解析<mappers />标签
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }

关于MappedStatement:

        MappedStatement 与Mapper配置⽂件中的⼀个select/update/insert/delete节点相对应。mapper中配置的标签都被封装到了此对象中,主要⽤途是描述⼀条SQL语句。

        回顾刚开始介绍的加载配置⽂件的过程中,会对mybatis-config.xml中的各个标签都进⾏解析,其中有mappers 标签⽤来引⼊mapper.xml⽂件或者配置mapper接⼝的⽬录。

<select id="getUser" resultType="user" >
    select * from user where id=#{id}
</select>

        这样的⼀个select标签会在初始化配置⽂件时被解析封装成⼀个MappedStatement对象,然后存储在Configuration对象的mappedStatements属性中,mappedStatements 是⼀个HashMap,存储时key=全限定类名+⽅法名,value =对应的MappedStatement对象。

Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>
("Mapped Statements collection")

        在 XMLConfigBuilder 中的处理:

private void parseConfiguration(XNode root) {
    try {
        //省略其他标签的处理
        mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
        throw new BuilderException("Error parsing SQL Mapper Configuration. Cause:" + e, e);
    }
}

        到此对xml配置⽂件的解析就结束了,回到步骤2.中调⽤的重载build⽅法:

// 5.调⽤的重载⽅法
public SqlSessionFactory build(Configuration config) {
    //创建了 DefaultSqlSessionFactory 对象,传⼊ Configuration 对象。
    return new DefaultSqlSessionFactory(config);
}

 2.1.2、执行SQL流程

关于SqlSession:

        SqlSession是⼀个接⼝,它有两个实现类:DefaultSqlSession (默认)和SqlSessionManager (弃⽤,不做介绍)。

        SqlSession是MyBatis中⽤于和数据库交互的顶层类,通常将它与ThreadLocal绑定,⼀个会话使⽤⼀个SqlSession,并且在使⽤完毕后需要close。

public class DefaultSqlSession implements SqlSession {

    private final Configuration configuration;

    private final Executor executor;
}

        SqlSession中的两个最重要的参数,configuration与初始化时的相同,Executor为执⾏器。

关于Executor:

        Executor也是⼀个接⼝,他有三个常⽤的实现类:

  1. BatchExecutor (重⽤语句并执⾏批量更新)
  2. ReuseExecutor (重⽤预处理语句 prepared statements)
  3. SimpleExecutor (普通的执⾏器,默认)

        继续分析,初始化完毕后,我们就要执⾏SQL 了:

SqlSession sqlSession = factory.openSession();

List<User> list = sqlSession.selectList("com.blnp.net.mapper.UserMapper.getUserByName");

获得 sqlSession:

//6. 进⼊ openSession ⽅法。
public SqlSession openSession() {
    //getDefaultExecutorType()传递的是SimpleExecutor
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null,
false);
}


//7. 进⼊penSessionFromDataSource。
//ExecutorType 为Executor的类型,TransactionIsolationLevel为事务隔离级别,autoCommit是否开启事务
//openSession的多个重载⽅法可以指定获得的SeqSession的Executor类型和事务的处理
private SqlSession openSessionFromDataSource(ExecutorType execType,
    TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try{
        final Environment environment = configuration.getEnvironment();
        final TransactionFactory transactionFactory =
        getTransactionFactoryFromEnvironment(environment);
        tx = transactionFactory.newTransaction(environment.getDataSource(),level, autoCommit);

        //根据参数创建指定类型的Executor
        final Executor executor = configuration.newExecutor(tx, execType);

        //返回的是 DefaultSqlSession
        return new DefaultSqlSession(configuration, executor, autoCommit);
    } catch(Exception e){
        closeTransaction(tx); // may have fetched a connection so lets call close()
    }
}

执⾏ sqlsession 中的 api:

 //8.进⼊selectList⽅法,多个重载⽅法。
 @Override
  public < E > List < E > selectList(String statement)
  {
      return this.selectList(statement, null);
  }
  @Override
  public < E > List < E > selectList(String statement, Object parameter)
  {
      return this.selectList(statement, parameter, RowBounds.DEFAULT);
  }
  @Override
  public < E > List < E > selectList(String statement, Object parameter, RowBounds rowBounds)
  {
      try
      {
          //根据传⼊的全限定名+⽅法名从映射的Map中取出MappedStatement对象
          MappedStatement ms = configuration.getMappedStatement(statement);

          //调⽤Executor中的⽅法处理
          //RowBounds是⽤来逻辑分⻚
          // wrapCollection(parameter)是⽤来装饰集合或者数组参数
          return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
      }
      catch (Exception e)
      {
          throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
      }
      finally
      {
          ErrorContext.instance().reset();
      }
  }

2.1.3、executor

        从代码 executor.query 进入查看:

//org.apache.ibatis.executor.BaseExecutor

//此⽅法在SimpleExecutor的⽗类BaseExecutor中实现
@Override
  public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {

    //根据传⼊的参数动态获得SQL语句,最后返回⽤BoundSql对象表示
    BoundSql boundSql = ms.getBoundSql(parameter);

    //为本次查询创建缓存的Key
    CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);

    //执行具体的查询
    return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
 }


//进⼊query的重载⽅法中
@SuppressWarnings("unchecked")
  @Override
  public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    if (queryStack == 0 && ms.isFlushCacheRequired()) {
      clearLocalCache();
    }
    List<E> list;
    try {
      queryStack++;
      list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
      if (list != null) {
        handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
      } else {
        //如果缓存中没有本次查找的值,那么从数据库中查询
        list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
      }
    } finally {
      queryStack--;
    }
    if (queryStack == 0) {
      for (DeferredLoad deferredLoad : deferredLoads) {
        deferredLoad.load();
      }
      // issue #601
      deferredLoads.clear();
      if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
        // issue #482
        clearLocalCache();
      }
    }
    return list;
  }


//从数据库查询
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    List<E> list;
    localCache.putObject(key, EXECUTION_PLACEHOLDER);
    try {
      //查询的⽅法
      list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
    } finally {
      localCache.removeObject(key);
    }

    //将查询结果放⼊缓存
    localCache.putObject(key, list);
    if (ms.getStatementType() == StatementType.CALLABLE) {
      localOutputParameterCache.putObject(key, parameter);
    }
    return list;
  }


// SimpleExecutor中实现⽗类的doQuery抽象⽅法
@Override
  public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    Statement stmt = null;
    try {
      Configuration configuration = ms.getConfiguration();

      //传⼊参数创建StatementHanlder对象来执⾏查询
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);

      //创建jdbc中的statement对象
      stmt = prepareStatement(handler, ms.getStatementLog());

      // StatementHandler 进⾏处理
      return handler.<E>query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }


//创建Statement的⽅法
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;

    //这条代码中的getConnection⽅法经过重重调⽤最后会调⽤openConnection⽅法,从连接池
中获 得连接。
    Connection connection = getConnection(statementLog);
    stmt = handler.prepare(connection, transaction.getTimeout());
    handler.parameterize(stmt);
    return stmt;
  }


//从连接池获得连接的⽅法
protected void openConnection() throws SQLException {
    if (log.isDebugEnabled()) {
      log.debug("Opening JDBC Connection");
    }

    //从连接池获得连接
    connection = dataSource.getConnection();
    if (level != null) {
      connection.setTransactionIsolation(level.getLevel());
    }
    setDesiredAutoCommit(autoCommmit);
  }

        上述的Executor.query()⽅法⼏经转折,最后会创建⼀个StatementHandler对象,然后将必要的参数传递给StatementHandler,使⽤StatementHandler来完成对数据库的查询,最终返回List结果集。从上⾯的代码中我们可以看出,Executor的功能和作⽤是:

(1、根据传递的参数,完成SQL语句的动态解析,⽣成BoundSql对象,供StatementHandler使⽤;

(2、为查询创建缓存,以提⾼性能

(3、创建JDBC的Statement连接对象,传递给*StatementHandler*对象,返回List查询结果。

2.1.4、StatementHandler

StatementHandler对象主要完成两个⼯作:

  • 对于JDBC的PreparedStatement类型的对象,创建的过程中,我们使⽤的是SQL语句字符串会包含若⼲个?占位符,我们其后再对占位符进⾏设值。StatementHandler通过 parameterize(statement)⽅法对 Statement 进⾏设值;
  • StatementHandler 通过 List query(Statement statement, ResultHandler resultHandler)⽅法来完成执⾏Statement,和将Statement对象返回的resultSet封装成List;

进⼊到 StatementHandler 的 parameterize(statement)⽅法的实现:

//org.apache.ibatis.executor.statement.PreparedStatementHandler

@Override
  public void parameterize(Statement statement) throws SQLException {
    //使⽤ParameterHandler对象来完成对Statement的设值
    parameterHandler.setParameters((PreparedStatement) statement);
  }

//org.apache.ibatis.scripting.defaults.DefaultParameterHandler
//对某⼀个Statement进⾏设置参数
@Override
  public void setParameters(PreparedStatement ps) {
    ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    if (parameterMappings != null) {
      for (int i = 0; i < parameterMappings.size(); i++) {
        ParameterMapping parameterMapping = parameterMappings.get(i);
        if (parameterMapping.getMode() != ParameterMode.OUT) {
          Object value;
          String prop
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值