6.MyBatis解析和運(yùn)行大致原理流程

1.前言

首先要理解MyBatis的運(yùn)行原理海渊,首先第一個(gè)需要掌握的是代理模式尔崔。因?yàn)橹暗囊恍┪恼吕锩妫覀儗懙陌咐喊椋锩娑加猩昝鱠ao層的接口勃痴。我們只是定義了一系列接口定義,而并沒有實(shí)現(xiàn)其邏輯接口热康。而這些都是MyBatis使用了代理模式幫我們實(shí)現(xiàn)了沛申。

補(bǔ)充下:了解代理模式看我之前的一篇關(guān)于代理模式的博文

代理模式 (Proxy)

2.構(gòu)建SqlSessionFactory過程

SqlSessionFactory創(chuàng)建流程

SqlSessionFactory是MyBatis的核心,主要提供SqlSession姐军。而SqlSessionFactory是采用生成器模式又稱構(gòu)建者模式生成铁材。

public static SqlSessionFactory buildSqlSessionFactory() throws IOException {
    InputStream inputStream = Resources.getResourceAsStream("config/mybatis-config.xml");
    return new SqlSessionFactoryBuilder().build(inputStream);
}

2.1SqlSessionFactory構(gòu)建步驟

  • 1.使用org.apache.ibatis.builder.xml.XMLConfigBuilder去解析配置xml屬性,并將解析的內(nèi)容存放在org.apache.ibatis.session.Configuration中

  • 2.使用Configuration對象去創(chuàng)建SqlSessionFactory奕锌。因?yàn)镾qlSessionFactory是接口著觉,所以MyBatis內(nèi)置了默認(rèn)的SqlSessionFactory實(shí)現(xiàn)類DefaultSqlSessionFactory

使用建造者模式的好處就是將生成SqlSessionFactory的過程與xml解析的過程分割開來,這樣便于代碼維護(hù)惊暴。

2.2構(gòu)建Configuration

org.apache.ibatis.builder.xml.XMLConfigBuilder重要的兩個(gè)方法

public Configuration parse() {
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true;
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
  }
private void parseConfiguration(XNode root) {
    try {
      //issue #117 read properties first
      propertiesElement(root.evalNode("properties"));
      Properties settings = settingsAsProperties(root.evalNode("settings"));
      loadCustomVfs(settings);
      typeAliasesElement(root.evalNode("typeAliases"));
      pluginElement(root.evalNode("plugins"));
      objectFactoryElement(root.evalNode("objectFactory"));
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      reflectorFactoryElement(root.evalNode("reflectorFactory"));
      settingsElement(settings);
      // read it after objectFactory and objectWrapperFactory issue #631
      environmentsElement(root.evalNode("environments"));
      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);
    }
  }

3.SqlSession運(yùn)行過程

SqlSession是獲取Mapper的重要接口饼丘。

因?yàn)樯厦娅@取的是DefaultSqlSessionFactory,所以使用到的是DefaultSqlSession

3.1 Mapper映射器使用動態(tài)代理

package org.apache.ibatis.binding.MapperProxyFactory

@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}

public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}

MapperProxy實(shí)現(xiàn)java.lang.reflect.InvocationHandler

 @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);
    }
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

4.SqlSession的重要對象

  • 1.Executor(執(zhí)行器對象)

由它來調(diào)度StatementHandler缴守、ParameterHandler葬毫、ResultHandler等來執(zhí)行對應(yīng)的SQL

  • 2.StatementHandler(數(shù)據(jù)庫會話器)

它的作用是使用數(shù)據(jù)庫的Statement(PreparedStatemnet)執(zhí)行操作镇辉,它是四大對象的核心屡穗,起到承上啟下的作用贴捡。

  • 3.ParameterHandler(參數(shù)處理器)

用于SQL對參數(shù)的處理

  • 4.ResultHandler(結(jié)果處理器)

是進(jìn)行最后數(shù)據(jù)集(ResultSet)的封裝返回

4.1Executor

Executor是我們在創(chuàng)建好SqlSessionFactory之后,使用factory.openSession()進(jìn)行創(chuàng)建村砂。在MyBatis存在三種執(zhí)行器烂斋。

1.simple。簡易執(zhí)行器础废,不配置就是默認(rèn)的執(zhí)行器

2.resuse汛骂。是一種執(zhí)行器重用預(yù)處理語句

3.batch。執(zhí)行器重用語句和批量更新评腺,它是針對批量專用的執(zhí)行器

  • openSession
 @Override
  public SqlSession openSession() {
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
  }

上面獲取的getDefaultExecutorType是protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;如果沒有設(shè)置執(zhí)行器的類型的話是simple

  • openSessionFromDataSource
 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);
      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();
    }
  }
  • newExecutor
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    if (ExecutorType.BATCH == executorType) {
      executor = new BatchExecutor(this, transaction);
    } else if (ExecutorType.REUSE == executorType) {
      executor = new ReuseExecutor(this, transaction);
    } else {
      executor = new SimpleExecutor(this, transaction);
    }
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }
  • SimpleExecutor內(nèi)部實(shí)現(xiàn)
  @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);
      stmt = prepareStatement(handler, ms.getStatementLog());
      return handler.<E>query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }
  private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;
    Connection connection = getConnection(statementLog);
    stmt = handler.prepare(connection, transaction.getTimeout());
    handler.parameterize(stmt);
    return stmt;
  }

MyBatis根據(jù)Configuration來構(gòu)建StatementHandler帘瞭,然后使用prepareStatement,對SQL編譯并對參數(shù)進(jìn)行初始化蒿讥。

實(shí)現(xiàn)過程:

  • 1.調(diào)用StatementHandler的prepare進(jìn)行預(yù)編譯和基礎(chǔ)設(shè)置
  • 2.調(diào)用StatementHandler的parameterize來設(shè)置參數(shù)并執(zhí)行
  • 3.利用ResultSetHandler組裝查詢結(jié)果給調(diào)用者完成一次查詢

4.2StatementHandler(數(shù)據(jù)庫會話器)

數(shù)據(jù)庫會話器是專門處理數(shù)據(jù)庫會話的

  • 創(chuàng)建StatementHandler實(shí)例

在包中org.apache.ibatis.session.Configuration

 public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
    statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
    return statementHandler;
  }

RoutingStatementHandler并不是一個(gè)真實(shí)的服務(wù)對象蝶念,其代碼只是做一個(gè)簡單工廠的職責(zé),使用方式不太好芋绸。

 public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {

    switch (ms.getStatementType()) {
      case STATEMENT:
        delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case PREPARED:
        delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case CALLABLE:
        delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      default:
        throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
    }

  }
  • 常用的PreparedStatementHandler

PreparedStatementHandler是繼承BaseStatementHandler

  @Override
  public Statement prepare(Connection connection, Integer transactionTimeout) throws SQLException {
    ErrorContext.instance().sql(boundSql.getSql());
    Statement statement = null;
    try {
      statement = instantiateStatement(connection);
      setStatementTimeout(statement, transactionTimeout);
      setFetchSize(statement);
      return statement;
    } catch (SQLException e) {
      closeStatement(statement);
      throw e;
    } catch (Exception e) {
      closeStatement(statement);
      throw new ExecutorException("Error preparing statement.  Cause: " + e, e);
    }
  }
 @Override
  protected Statement instantiateStatement(Connection connection) throws SQLException {
    String sql = boundSql.getSql();
    if (mappedStatement.getKeyGenerator() instanceof Jdbc3KeyGenerator) {
      String[] keyColumnNames = mappedStatement.getKeyColumns();
      if (keyColumnNames == null) {
        return connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
      } else {
        return connection.prepareStatement(sql, keyColumnNames);
      }
    } else if (mappedStatement.getResultSetType() != null) {
      return connection.prepareStatement(sql, mappedStatement.getResultSetType().getValue(), ResultSet.CONCUR_READ_ONLY);
    } else {
      return connection.prepareStatement(sql);
    }
  }

4.3 ParameterHandler

設(shè)置SQL參數(shù)媒殉。handler.parameterize(stmt);

  public void parameterize(Statement statement) throws SQLException {
    parameterHandler.setParameters((PreparedStatement) statement);
  }
  • 設(shè)置參數(shù)是使用的DefaultParameterHandler
  @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 propertyName = parameterMapping.getProperty();
          if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params
            value = boundSql.getAdditionalParameter(propertyName);
          } else if (parameterObject == null) {
            value = null;
          } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
            value = parameterObject;
          } else {
            MetaObject metaObject = configuration.newMetaObject(parameterObject);
            value = metaObject.getValue(propertyName);
          }
          TypeHandler typeHandler = parameterMapping.getTypeHandler();
          JdbcType jdbcType = parameterMapping.getJdbcType();
          if (value == null && jdbcType == null) {
            jdbcType = configuration.getJdbcTypeForNull();
          }
          try {
            typeHandler.setParameter(ps, i + 1, value, jdbcType);
          } catch (TypeException e) {
            throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
          } catch (SQLException e) {
            throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
          }
        }
      }
    }
  }

4.4ResultSetHandler

用于組裝數(shù)據(jù)返回的結(jié)果集到對應(yīng)的POJO上

public interface ResultSetHandler {

  <E> List<E> handleResultSets(Statement stmt) throws SQLException;

  <E> Cursor<E> handleCursorResultSets(Statement stmt) throws SQLException;

  void handleOutputParameters(CallableStatement cs) throws SQLException;

}

宏觀的看,MyBatis的整理架構(gòu)圖如下:

MyBatis整體架構(gòu)圖
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末摔敛,一起剝皮案震驚了整個(gè)濱河市廷蓉,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌马昙,老刑警劉巖桃犬,帶你破解...
    沈念sama閱讀 221,273評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異行楞,居然都是意外死亡疫萤,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,349評論 3 398
  • 文/潘曉璐 我一進(jìn)店門敢伸,熙熙樓的掌柜王于貴愁眉苦臉地迎上來扯饶,“玉大人,你說我怎么就攤上這事池颈∥残颍” “怎么了?”我有些...
    開封第一講書人閱讀 167,709評論 0 360
  • 文/不壞的土叔 我叫張陵躯砰,是天一觀的道長每币。 經(jīng)常有香客問我,道長琢歇,這世上最難降的妖魔是什么兰怠? 我笑而不...
    開封第一講書人閱讀 59,520評論 1 296
  • 正文 為了忘掉前任梦鉴,我火速辦了婚禮,結(jié)果婚禮上揭保,老公的妹妹穿的比我還像新娘肥橙。我一直安慰自己,他們只是感情好秸侣,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,515評論 6 397
  • 文/花漫 我一把揭開白布存筏。 她就那樣靜靜地躺著,像睡著了一般味榛。 火紅的嫁衣襯著肌膚如雪椭坚。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,158評論 1 308
  • 那天搏色,我揣著相機(jī)與錄音善茎,去河邊找鬼。 笑死频轿,一個(gè)胖子當(dāng)著我的面吹牛垂涯,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播略吨,決...
    沈念sama閱讀 40,755評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼集币,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了翠忠?” 一聲冷哼從身側(cè)響起鞠苟,我...
    開封第一講書人閱讀 39,660評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎秽之,沒想到半個(gè)月后当娱,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,203評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡考榨,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,287評論 3 340
  • 正文 我和宋清朗相戀三年跨细,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片河质。...
    茶點(diǎn)故事閱讀 40,427評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡冀惭,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出掀鹅,到底是詐尸還是另有隱情散休,我是刑警寧澤,帶...
    沈念sama閱讀 36,122評論 5 349
  • 正文 年R本政府宣布乐尊,位于F島的核電站戚丸,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏扔嵌。R本人自食惡果不足惜限府,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,801評論 3 333
  • 文/蒙蒙 一夺颤、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧胁勺,春花似錦世澜、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,272評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽势告。三九已至蛇捌,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間咱台,已是汗流浹背络拌。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留回溺,地道東北人春贸。 一個(gè)月前我還...
    沈念sama閱讀 48,808評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像遗遵,于是被迫代替她去往敵國和親萍恕。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,440評論 2 359

推薦閱讀更多精彩內(nèi)容