Mybatis核心源碼分析

一、介紹

       mybatis作爲一款半自動化數據庫持久層框架,提供了完整的JDBC操作,對參數解析,sql預編譯,返回值解析,數據庫事務

的支持,還有對於session的管理,數據緩存的處理;有xml和註解兩種配置方式,幾乎屏蔽了JDBC的操作;正式因爲這種靈活使

它廣受國內互聯網公司的青睞;

二、核心類

      1.SqlSessionFactoryBuilder

         通過讀取xml文件流或者創建Configuration類的方式注入mybatis的全局配置文件

         new SqlSessionFactoryBuilder().build("xml文件路徑")或者new SqlSessionFactoryBuilder().build("configuration類")

         返回值爲SqlSessionFactory

      2.SqlSessionFactory

         SqlSession的工廠類,可以返回一個session(數據庫會話)

         兩個具體的實現類DefaultSqlSessionFactory和SqlSessionManager

         DefaultSqlSessionFactory:會根據mybatis的配置創建session

//execType是Configuration配置文件中指定的執行器
//level級別(事務的級別,根據數據的事務隔離級別不同)
//autoCommit是否自動提交事務
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);
      //根據事務和執行器創建實例
      final Executor executor = configuration.newExecutor(tx, execType);
      //根據以上條件創建一個session
      return new DefaultSqlSession(configuration, executor, autoCommit);
    } catch (Exception e) {
      //如果上述代碼出現異常,那麼關閉事務
      closeTransaction(tx); // may have fetched a connection so lets call close()
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

      SqlSessionManager:會通過ThreadLocal創建session,保證創建的session只有當前線程使用(session本身線程不安全)

                                          這樣session的生命週期就會跟隨當前線程

      3.SqlSession

      mybatis提供的操作數據庫增刪改查的頂層接口,內部有我們配置和具體的執行器

      4.Executor

      mybatis提供的具體操作數據庫的類,增刪改查,事務提交,回滾等;有以下四個實現

      SimpleExecutor:簡單的數據庫操作,沒有緩存,使用完釋放所有資源

      BatchExecutor:只提供了增刪改的功能,不支持查詢操作

      ReuseExecutor:對於statement的緩存,用map封裝

private void putStatement(String sql, Statement stmt) {
    statementMap.put(sql, stmt);
  }

      CachingExecutor:會對結果查詢結果做緩存,如果在同一個緩存中有,那麼直接使用緩存

@Override
  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
    Cache cache = ms.getCache();
    if (cache != null) {
      flushCacheIfRequired(ms);
      if (ms.isUseCache() && resultHandler == null) {
        ensureNoOutParams(ms, parameterObject, boundSql);
        @SuppressWarnings("unchecked")
        //如果緩存中有,那麼直接返回數據,不再查詢數據庫
        List<E> list = (List<E>) tcm.getObject(cache, key);
        if (list == null) {
          list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
    return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

      5.StatementHandler

      對statement對象的操作類,對應也有四個實現,在介紹StatementHandler內容之前先聊以下statement的內容

      statement:類路徑 java.sql,是具體執行某一個確定的sql,並且返回一個結果;這裏的sql是即將傳遞給數據庫執行的語句

      有兩個實現類prepareStatement和CallableStatement

      prepareStatement:預編譯好的sql

      CallableStatement:預編譯好的存儲過程

      StatementHandler就是對以上Statement的操作,以下爲StatementHandler的四個實現類

      SimpleStatementHandler:用於處理JDBC中簡單的statement接口

      CallableStatementHandler:用於處理存儲過程的CallableStatement

      PrepareStatementHandler:用於處理我們預編譯好的PrepareStatement

      RoutingStatementHandler:沒有實際邏輯,只負責以上三個handler的調度

三、源碼跟蹤一次請求

      簡單的mybatis一次完整請求

@Test
    public void testGet() throws Exception{
        //1創建mybatis的構建器
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //2解析具體的xml或者configuration類(配置有數據庫連接,mapper文件地址)
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
        //3打開一個會話連接
        SqlSession session = sqlSessionFactory.openSession();
        //4獲取mapper的代理對象
        WmsUserConfMapper mapper = session.getMapper(WmsUserConfMapper.class);
        //5通過代理對象執行具體的sql
        mapper.get("a");
    }

      第一,二,三可以自己跟一下源碼,這裏不做過多解釋,直接從獲取mapper代理對象開始

     通過上邊對session的講解可知,當前獲得是一個DefaultSqlSession,進入getMapper方法

@Override
  public <T> T getMapper(Class<T> type) {
    return configuration.getMapper(type, this);
  }

     再進入到configuration.getMapper()方法中

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
  }

     進入mapper註冊,也就是創建代理對象的方法

@SuppressWarnings("unchecked")
  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }

       mapper代理對象創建完畢,接下來進入重點,調用代理對象mapper.get("a");方法,我們debug進來,看到invoke方法

 @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    //1.緩存mapper的數據,第二次進入相同mapper直接訪問緩存,提高效率
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    //2.執行具體邏輯
    return mapperMethod.execute(sqlSession, args);
  }

        先看下上述代碼塊中步驟1對應的源碼,第一次訪問mapper會創建一個mapperMethod,源碼如下

public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
    //根據config配置,接口,和方法,創建當前方法的mapperStatement對象
    this.command = new SqlCommand(config, mapperInterface, method);
    //根據config配置,接口,和方法,獲取當前mapper接口方法對應的簽名信息
    this.method = new MethodSignature(config, mapperInterface, method);
  }

       new SqlCommand()和new MethodSignature()源碼,可自行跟蹤一下,沒什麼複雜的邏輯

      步驟2執行的源碼如下

public Object execute(SqlSession sqlSession, Object[] args) {
    Object result; 
    //1.type是根據解析mapper對應的xml文件標籤得到的
    switch (command.getType()) {
      case INSERT: {
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.insert(command.getName(), param));
        break;
      }
      case UPDATE: {
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.update(command.getName(), param));
        break;
      }
      case DELETE: {
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.delete(command.getName(), param));
        break;
      }
      //2.我們這裏是select直接看這塊邏輯
      case SELECT:
         //3.根據方法簽名上的返回值決定執行不同的方法
        if (method.returnsVoid() && method.hasResultHandler()) {
          executeWithResultHandler(sqlSession, args);
          result = null;
        } else if (method.returnsMany()) {
          result = executeForMany(sqlSession, args);
        } else if (method.returnsMap()) {
          result = executeForMap(sqlSession, args);
        } else if (method.returnsCursor()) {
          result = executeForCursor(sqlSession, args);
        } else {
          //4.我們這裏沒有返回值,並且返回值沒有resultHandler
          //5.解析方法上的參數
          Object param = method.convertArgsToSqlCommandParam(args);
          //6.執行session的查詢
          result = sqlSession.selectOne(command.getName(), param);
          if (method.returnsOptional()
              && (result == null || !method.getReturnType().equals(result.getClass()))) {
            result = Optional.ofNullable(result);
          }
        }
        break;
      case FLUSH:
        result = sqlSession.flushStatements();
        break;
      default:
        throw new BindingException("Unknown execution method for: " + command.getName());
    }
    if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
      throw new BindingException("Mapper method '" + command.getName()
          + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
    }
    return result;
  }

        我們跟一下上述5參數解析部分的源碼,如下

public Object getNamedParams(Object[] args) {
    //當前方法的參數保存在一個有序的map中即names,value爲屬性名稱
    final int paramCount = names.size();
    //判斷names的大小來決定邏輯
    if (args == null || paramCount == 0) {
      return null;
    } else if (!hasParamAnnotation && paramCount == 1) {
      return args[names.firstKey()];
    } else {
      final Map<String, Object> param = new ParamMap<>();
      int i = 0;
      for (Map.Entry<Integer, String> entry : names.entrySet()) {
        //通過循環將屬性名稱和值存放到map中使用
        param.put(entry.getValue(), args[entry.getKey()]);
        // add generic param names (param1, param2, ...)
        final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1);
        // ensure not to overwrite parameter named with @Param
        if (!names.containsValue(genericParamName)) {
          param.put(genericParamName, args[entry.getKey()]);
        }
        i++;
      }
       //返回一個map對象
      return param;
    }
  }

        上述第6步執行session的查詢方法,我們在進入源碼,一直走到DefaultSqlSession中,如下

@Override
  public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
     //通過配置文件獲取mapper中對應的statement的sql語句
      MappedStatement ms = configuration.getMappedStatement(statement);
      //通過執行器查詢數據
      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();
    }
  }

        進入executor.query方法,我們這裏進入的是CachingExecutor類中,源碼如下

@Override
  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
    //構建sql,及參數數據,封裝爲boundSql對象
    BoundSql boundSql = ms.getBoundSql(parameterObject);
    //創建緩存
    CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
    //執行查詢
    return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

    進入query方法,如下

@Override
  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
    //獲取緩存
    Cache cache = ms.getCache();
    if (cache != null) {
      //刷新緩存
      flushCacheIfRequired(ms);
      if (ms.isUseCache() && resultHandler == null) {
        ensureNoOutParams(ms, boundSql);
        @SuppressWarnings("unchecked")
        List<E> list = (List<E>) tcm.getObject(cache, key);
        if (list == null) {
          list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
    //這裏真正執行的SimpleExecutor的查詢
    return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

     進入delegate.query()方法,這裏走到了SimpleExecutor的父類BaseExecutor

   

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;
  }

     進入queryFromDataBase方法

​

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;
  }

[點擊並拖拽以移動]
​

       進入doQuery方法,到了SimpleExecutor類中

@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();
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      //通過預編譯的方式,構建出完整的sql語句
      stmt = prepareStatement(handler, ms.getStatementLog());
      //調用到PrepareStatementHandler進行sql的查詢操作
      return handler.query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }

        進入到PrepareStatementHandler進行查詢操作,會調用到PrepareStatement的execute執行查詢,最終將結果返回,並

        用ResultSetHandler處理請求的結果

四、總結

    第一次完完整整一步一步的走了一遍mybatis的源碼,感覺收貨還是蠻大的,一遍debug一遍記錄,掃了很多盲點,走完一遍

    後發現對於數據庫和mybatis這塊的內容又有了新的認識,不知不覺過去了三個小時了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章