MyBatis 源碼分析篇 4:Mapper 方法執(zhí)行

通過上一篇文章 MyBatis 源碼分析篇 3:getMapper 我們已經知道 MyBatis 通過動態(tài)代理的方式獲取 Mapper 實例灯萍。在這一篇文章中我們就來具體討論其動態(tài)代理的具體實現(xiàn)和 Mapper 中方法是如何執(zhí)行的。

以下面代碼為入口齿风,我們來進行 debug 代碼跟入:

List<Author> author = mapper.selectAllTest();

selectAllTest 方法的 sql 如下:

select id, name, sex, phone from author

不出意外的我們會首先進入代理類 org.apache.ibatis.binding.MapperProxy 的 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);
    }
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

首先我們需要注意一下該類救斑,該類持有一個 SqlSession 類型的成員變量诊笤,并在構造方法中進行了賦值:

  private final SqlSession sqlSession;
  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethod> methodCache;

  public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
    this.sqlSession = sqlSession;
    this.mapperInterface = mapperInterface;
    this.methodCache = methodCache;
  }

這也完全在我們意料之中,不知道大家還記不記得我們在 MyBatis 源碼分析篇 2:SqlSession 中討論的,SqlSession 包含了執(zhí)行數(shù)據庫操作的所有方法晾匠。那么我們反過來想一下梯刚,MapperProxy 代理類是要對我們在 Mapper 中聲明的方法進行執(zhí)行,而數(shù)據庫操作的方法都在 SqlSession 中澜共,那么它就一定要持有一個 SqlSession锥腻,來調用 SqlSession 中對應的方法!

接下來我們就來驗證一下我們的猜想京革。我們再次回到 MapperProxy 的 invoke 方法。注意最后一行代碼:return mapperMethod.execute(sqlSession, args);匹摇,跟入該行代碼廊勃,會進入 org.apache.ibatis.binding.MapperMethod 類的 execute(SqlSession sqlSession, Object[] args) 方法:

  public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    switch (command.getType()) {
      //其余類型略...
      case SELECT:
        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 {
          Object param = method.convertArgsToSqlCommandParam(args);
          result = sqlSession.selectOne(command.getName(), param);
        }
        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;
  }

在上面的代碼中坡垫,因為我們測試執(zhí)行的是返回值為 List 類型的 select 方法,那么接著會進入第 10 行代碼:result = executeForMany(sqlSession, args); 其實現(xiàn)為:

  private <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
    List<E> result;
    Object param = method.convertArgsToSqlCommandParam(args);
    if (method.hasRowBounds()) {
      RowBounds rowBounds = method.extractRowBounds(args);
      result = sqlSession.<E>selectList(command.getName(), param, rowBounds);
    } else {
      result = sqlSession.<E>selectList(command.getName(), param);
    }
    // issue #510 Collections & arrays support
    if (!method.getReturnType().isAssignableFrom(result.getClass())) {
      if (method.getReturnType().isArray()) {
        return convertToArray(result);
      } else {
        return convertToDeclaredCollection(sqlSession.getConfiguration(), result);
      }
    }
    return result;
  }

因為我們并沒有綁定 RowBounds胎源,那么會執(zhí)行第 8 行代碼:result = sqlSession.<E>selectList(command.getName(), param);屿脐。果然的诵,到這一步就驗證了我們之前的猜想,它果然是調用了 SqlSession 的 selectList 方法西疤!

至此,代碼執(zhí)行就回到了 SqlSession 的 selectList扰她,我們在之后的文章 MyBatis 源碼分析篇 5:Mapper 方法執(zhí)行之 Executor 詳細討論其底層實現(xiàn)芭碍。

附:

當前版本:mybatis-3.5.0
官網文檔:MyBatis
項目實踐:MyBatis Learn
手寫源碼:MyBatis 簡易實現(xiàn)

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末窖壕,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子鸳吸,更是在濱河造成了極大的恐慌速勇,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,509評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件贡羔,死亡現(xiàn)場離奇詭異,居然都是意外死亡猴蹂,警方通過查閱死者的電腦和手機楣嘁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評論 3 394
  • 文/潘曉璐 我一進店門逐虚,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人叭爱,你說我怎么就攤上這事买雾。” “怎么了漓穿?”我有些...
    開封第一講書人閱讀 163,875評論 0 354
  • 文/不壞的土叔 我叫張陵晃危,是天一觀的道長。 經常有香客問我震叮,道長鳍鸵,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,441評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮乌妒,結果婚禮上,老公的妹妹穿的比我還像新娘古掏。我一直安慰自己侦啸,他們只是感情好丧枪,可當我...
    茶點故事閱讀 67,488評論 6 392
  • 文/花漫 我一把揭開白布拧烦。 她就那樣靜靜地躺著钝计,像睡著了一般。 火紅的嫁衣襯著肌膚如雪债沮。 梳的紋絲不亂的頭發(fā)上本鸣,一...
    開封第一講書人閱讀 51,365評論 1 302
  • 那天,我揣著相機與錄音闷煤,去河邊找鬼。 笑死命爬,一個胖子當著我的面吹牛曹傀,可吹牛的內容都是我干的。 我是一名探鬼主播饲宛,決...
    沈念sama閱讀 40,190評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼皆愉,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了艇抠?” 一聲冷哼從身側響起幕庐,我...
    開封第一講書人閱讀 39,062評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎家淤,沒想到半個月后异剥,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 45,500評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡絮重,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,706評論 3 335
  • 正文 我和宋清朗相戀三年冤寿,在試婚紗的時候發(fā)現(xiàn)自己被綠了青伤。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片督怜。...
    茶點故事閱讀 39,834評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖狠角,靈堂內的尸體忽然破棺而出号杠,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 35,559評論 5 345
  • 正文 年R本政府宣布姨蟋,位于F島的核電站屉凯,受9級特大地震影響,放射性物質發(fā)生泄漏眼溶。R本人自食惡果不足惜悠砚,卻給世界環(huán)境...
    茶點故事閱讀 41,167評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望偷仿。 院中可真熱鬧哩簿,春花似錦、人聲如沸酝静。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽别智。三九已至宗苍,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間薄榛,已是汗流浹背讳窟。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留敞恋,地道東北人丽啡。 一個月前我還...
    沈念sama閱讀 47,958評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像硬猫,于是被迫代替她去往敵國和親补箍。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,779評論 2 354