Mybatis原理之參數(shù)處理

前言

Mybatis參數(shù)處理是Mybatis核心內(nèi)容福侈,圍繞著Mybatis的面試題也是層出不窮。接下來(lái)跟隨源碼看下Mybatis是如何處理參數(shù)的浓领。

代碼示例

Mapper

ApplicationEntity getByCode(@Param("code") String code);

XML

<select id="getByCode" resultMap="BaseResultMap">  
    SELECT  <include refid="Base_Column_List"/>
    FROM application
    WHERE code =#{code} AND deleted =0
</select>

JunitTest


@ActiveProfiles("dev")
@SpringBootTest
@RunWith(SpringRunner.class)
public class MybatisTest {

    //這里注入的實(shí)際上是一個(gè)代理類
    @Autowired
    private ApplicationMapper applicationMapper;

    @Test
    public void testMybatis(){
        ApplicationEntity applicationEntity = applicationMapper.getByCode("w1111");
        System.out.println(applicationEntity);
    }
}
  • 這里注入的實(shí)際上是一個(gè)代理類犯戏,這個(gè)代理類是在應(yīng)用啟動(dòng)的時(shí)候spring發(fā)現(xiàn)其他bean注入了這個(gè)類,就通過(guò)BeanFactory.getBean()娘汞,再通過(guò)FactoryBean(MapperFactoryBean).getObject()歹茶,最后通過(guò)動(dòng)態(tài)代理注入得到。Mybatis參數(shù)處理

idea debug進(jìn)入下一步你弦,可以發(fā)現(xiàn)進(jìn)入了MapperProxy的invoke方法惊豺。

Mapper#invoke.png
@Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      //這里的method.getDeclaringClass()的值是com.xt.algorithm.mapper.LoanApplicationMapper
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {
        //isDefaultMethod(method)返回false
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    //將MapperMethod緩存起來(lái) 
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    //最后執(zhí)行mapperMethos.execute()方法
    return mapperMethod.execute(sqlSession, args);
  }

private MapperMethod cachedMapperMethod(Method method) {
    return methodCache.computeIfAbsent(method, k -> new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
  }

接下來(lái)看下MapperMethod.execute()方法是如何處理參數(shù)的。

public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    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;
      }
      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);
          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());
    }
    //...
    return result;
  }

可以看到對(duì)于參數(shù)處理禽作,都是通過(guò)Object param = method.convertArgsToSqlCommandParam(args);去處理的尸昧,那么我們看下這個(gè)方法到底做了什么操作。

public Object convertArgsToSqlCommandParam(Object[] args) {
      return paramNameResolver.getNamedParams(args);
}

public Object getNamedParams(Object[] args) {
    final int paramCount = names.size();
    if (args == null || paramCount == 0) {
      //如果沒(méi)有入?yún)⒖醭ィ蛘叻椒ǘx參數(shù)個(gè)數(shù)為0烹俗,直接返回null
      return null;
    } else if (!hasParamAnnotation && paramCount == 1) {
      //如果沒(méi)有使用@Param注解碍沐,且參數(shù)個(gè)數(shù)為1個(gè),直接返回入?yún)?      return args[names.firstKey()];
    } else {
      //否則衷蜓,遍歷方法names
      final Map<String, Object> param = new ParamMap<>();
      int i = 0;
      for (Map.Entry<Integer, String> entry : names.entrySet()) {
        //這里將names的鍵值對(duì)放入param中
        param.put(entry.getValue(), args[entry.getKey()]);
        // add generic param names (param1, param2, ...)
        //并添加{"param1":entay.getKey()}形式放入param中
        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++;
      }
      return param;
    }
  }
ParamNamesResolver#getNamedParams.png

可以看到ParamNameResolver.getNamedParams()方法的入?yún)rgs就是mapper接口上方法值累提。

names.png

names是一個(gè)SortedMap,內(nèi)部的鍵值對(duì)磁浇,key為參數(shù)在接口方法中的索引位置(方法入?yún)⒅械牡趲讉€(gè)參數(shù)斋陪,從0開(kāi)始),value為@Param的value值(如果沒(méi)有使用@Param注解置吓,默認(rèn)為arg0,arg1...)无虚。

這一部分可從ParamNameResolver的構(gòu)造函數(shù)中看出。

public ParamNameResolver(Configuration config, Method method) {
    //獲取方法參數(shù)類型
    final Class<?>[] paramTypes = method.getParameterTypes();
    //獲取方法參數(shù)上的注解
    final Annotation[][] paramAnnotations = method.getParameterAnnotations();
    final SortedMap<Integer, String> map = new TreeMap<>();
    int paramCount = paramAnnotations.length;
    // get names from @Param annotations
    for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
      //從@Param注解上獲取value屬性值衍锚,并給name字段賦值
      String name = null;
      for (Annotation annotation : paramAnnotations[paramIndex]) {
        if (annotation instanceof Param) {
          hasParamAnnotation = true;
          name = ((Param) annotation).value();
          break;
        }
      }
      if (name == null) {
        // @Param was not specified.
        //如果沒(méi)參數(shù)沒(méi)使用@Param注解
        if (config.isUseActualParamName()) {
          //從method中取出參數(shù)名稱友题,一般為arg0,arg1 ...
          name = getActualParamName(method, paramIndex);
        }
        if (name == null) {
          // use the parameter index as the name ("0", "1", ...)
          // gcode issue #71
          //如果前面幾個(gè)操作給name賦值都失敗了,最后使用下標(biāo)作為鍵值對(duì)的value  
          name = String.valueOf(map.size());
        }
      }
      //key為參數(shù)下標(biāo)戴质,value為@Param注解value值或者mybatis指定默認(rèn)值
      map.put(paramIndex, name);
    }
    names = Collections.unmodifiableSortedMap(map);
  }

names鍵值對(duì)總結(jié)

從上述構(gòu)造方法可以看出度宦,names中的鍵值對(duì)應(yīng)該是{"0","paramValue"}或者{"1":"arg1"}這樣。

getNamedParams方法返回的map中的鍵值對(duì)應(yīng)該是{"paramValue":"0"}或者{"param1":"1"}這樣告匠。

其中:paramValue是指@Param注解的value屬性戈抄。param1是mybatis通用的參數(shù)key。

getNamedParams返回的數(shù)據(jù)類型有以下幾種:

  • null:mapper方法中沒(méi)定義參數(shù)或者入?yún)閚ull后专。
  • 除了map划鸽、null以外的其他Object類型,包括基本數(shù)據(jù)類型和java 對(duì)象:當(dāng)入?yún)⒅袃H有一個(gè)參數(shù)戚哎,而且沒(méi)有使用@Param注解時(shí)裸诽。
  • map:使用了@Param注解或者mapper方法入?yún)⒉恢挂粋€(gè)。

SELECT方法中的參數(shù)繼續(xù)處理

SELECT類型的方法最后都在SqlSession的slectList方法中進(jìn)行統(tǒng)一處理型凳。

public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      //先根據(jù)statement從configuration中獲取MappedStatement
      //這里的statement就是mapper接口名.方法名
      //String statementId = mapperInterface.getName() + "." + methodName;
      MappedStatement ms = configuration.getMappedStatement(statement); 
      //這里的wrapCollection對(duì)方法又進(jìn)行了一層包裝
      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();
    }
  }

這里有必要說(shuō)明一下方法的入?yún)ⅲ?/p>

  • statement:就是statementId:mapper接口名.方法名丈冬。詳見(jiàn)org.apache.ibatis.binding.MapperMethod.SqlCommand#resolveMappedStatement
  • parameter:就是前面getNamedParams方法返回的數(shù)據(jù),可能是null啰脚,map以及其他object類型的數(shù)據(jù)殷蛇。
  • rowBounds:分頁(yè)相關(guān)的數(shù)據(jù),這里是默認(rèn)的rowBounds橄浓,不分頁(yè)。
private Object wrapCollection(final Object object) {
    //在對(duì)selectList方法入?yún)⑦M(jìn)行包裝前亮航,先判斷參數(shù)類型
    if (object instanceof Collection) {
      //這里判斷了是不是collection類型荸实,如果是則在外面使用map包一層,key為collection缴淋,value為入?yún)⒅底几_@里僅當(dāng)getNamedParams返回的是Object類型時(shí)才可能進(jìn)入泄朴,就是說(shuō)mapper方法的入?yún)⒅挥幸粋€(gè),而且沒(méi)有使用@Param注解
      StrictMap<Object> map = new StrictMap<>();
      map.put("collection", object);
      if (object instanceof List) {
        //這里再次判斷是否是List子類型露氮,如果是的話祖灰,再添加一個(gè)key為"list"的鍵值對(duì),方便動(dòng)態(tài)SQL中的<foreach>等使用
        map.put("list", object);
      }
      return map;
    } else if (object != null && object.getClass().isArray()) {
      //如果是數(shù)組的話畔规,也會(huì)用map包裝一層局扶,key為"array"  
      StrictMap<Object> map = new StrictMap<>();
      map.put("array", object);
      return map;
    }
    return object;
  }

總的來(lái)說(shuō),wrapCollection方法就是對(duì)getNamedParams處理后的參數(shù)再次進(jìn)行處理叁扫,如果是數(shù)組或者Collection對(duì)象三妈,則在外面用map包裝一層,方便后續(xù)的動(dòng)態(tài)SQL使用參數(shù)莫绣。

緊接著就到了SimpleExecutor的doQuery方法了

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默認(rèn)是RoutingStatementHandler畴蒲,被代理類是PreparedStatementHandler
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      //調(diào)用內(nèi)部私有方法
      stmt = prepareStatement(handler, ms.getStatementLog());
      //查詢
      return handler.query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }

private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;
    //底層數(shù)據(jù)庫(kù)服務(wù)獲取數(shù)據(jù)庫(kù)連接connection
    Connection connection = getConnection(statementLog);
    //調(diào)用底層connection的prepareStatement方法預(yù)編譯SQL
    stmt = handler.prepare(connection, transaction.getTimeout());
    //handler 參數(shù)化
    handler.parameterize(stmt);
    return stmt;
  }

DefaultParameterHandler.setParameters()方法

public void setParameters(PreparedStatement ps) {
    ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    if (parameterMappings != null) {
      //遍歷 ParameterMapping,ParameterMapping中包含屬性对室,javaType模燥、jdbcType等 
      for (int i = 0; i < parameterMappings.size(); i++) {
        ParameterMapping parameterMapping = parameterMappings.get(i);
        if (parameterMapping.getMode() != ParameterMode.OUT) {
          Object value;
          //SQL中參數(shù)名,#{參數(shù)名}
          String propertyName = parameterMapping.getProperty();
          if (boundSql.hasAdditionalParameter(propertyName)) {
              //動(dòng)態(tài)SQL時(shí)掩宜,解析時(shí)會(huì)自動(dòng)假如其他的參數(shù)值
              // issue #448 ask first for additional params
            value = boundSql.getAdditionalParameter(propertyName);
          } else if (parameterObject == null) {
            //如果mapper方法的入?yún)arameterObject為空涧窒,則直接返回null
            value = null;
          } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
            //如果parameterObject是簡(jiǎn)單基本類型的話,則value直接等于parameterObject
            value = parameterObject;
          } else {
            //如果parameterObject是map或者java bean等復(fù)雜類型的話锭亏,構(gòu)造MetaObject纠吴,方便通過(guò)屬性或者多層嵌套(如user.name)取值
            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 {
            //通過(guò)typehandler set參數(shù)值到SQL中
            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);
          }
        }
      }
    }
  }

緊接著就是PreparedStatementHandler的query方法。

public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
    PreparedStatement ps = (PreparedStatement) statement;
    //這里直接調(diào)用execute方法慧瘤,最后通過(guò)數(shù)據(jù)庫(kù)底層驅(qū)動(dòng)(如mysql)的PreparedStatement實(shí)現(xiàn)類完成execute方法戴已。執(zhí)行SQL
    ps.execute();
    return resultSetHandler.handleResultSets(ps);
  }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市锅减,隨后出現(xiàn)的幾起案子糖儡,更是在濱河造成了極大的恐慌,老刑警劉巖怔匣,帶你破解...
    沈念sama閱讀 216,372評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件握联,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡每瞒,警方通過(guò)查閱死者的電腦和手機(jī)金闽,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)剿骨,“玉大人代芜,你說(shuō)我怎么就攤上這事∨ɡ” “怎么了挤庇?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,415評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵钞速,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我嫡秕,道長(zhǎng)渴语,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,157評(píng)論 1 292
  • 正文 為了忘掉前任昆咽,我火速辦了婚禮驾凶,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘潮改。我一直安慰自己狭郑,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布汇在。 她就那樣靜靜地躺著翰萨,像睡著了一般。 火紅的嫁衣襯著肌膚如雪糕殉。 梳的紋絲不亂的頭發(fā)上亩鬼,一...
    開(kāi)封第一講書(shū)人閱讀 51,125評(píng)論 1 297
  • 那天,我揣著相機(jī)與錄音阿蝶,去河邊找鬼雳锋。 笑死,一個(gè)胖子當(dāng)著我的面吹牛羡洁,可吹牛的內(nèi)容都是我干的玷过。 我是一名探鬼主播,決...
    沈念sama閱讀 40,028評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼筑煮,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼辛蚊!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起真仲,我...
    開(kāi)封第一講書(shū)人閱讀 38,887評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤袋马,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后秸应,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體虑凛,經(jīng)...
    沈念sama閱讀 45,310評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評(píng)論 2 332
  • 正文 我和宋清朗相戀三年软啼,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了桑谍。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,690評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡焰宣,死狀恐怖霉囚,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情匕积,我是刑警寧澤盈罐,帶...
    沈念sama閱讀 35,411評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站闪唆,受9級(jí)特大地震影響盅粪,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜悄蕾,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評(píng)論 3 325
  • 文/蒙蒙 一票顾、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧帆调,春花似錦奠骄、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至芹务,卻和暖如春蝉绷,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背枣抱。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,812評(píng)論 1 268
  • 我被黑心中介騙來(lái)泰國(guó)打工熔吗, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人佳晶。 一個(gè)月前我還...
    沈念sama閱讀 47,693評(píng)論 2 368
  • 正文 我出身青樓桅狠,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親轿秧。 傳聞我的和親對(duì)象是個(gè)殘疾皇子中跌,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評(píng)論 2 353

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