1. 程式人生 > 程式設計 >Mybatis之方法如何對映到XML

Mybatis之方法如何對映到XML

前言

上文Mybatis之Mapper介面如何執行SQL中瞭解到,Mapper通過動態代理的方式執行SQL,但是並沒有詳細的介紹方法是如何做對映的,方法包括:方法名,返回值,引數等;這些都是如何同xxMapper.xml進行關聯的。

方法名對映

上文中提到快取MapperMethod的目的是因為需要例項化SqlCommand和MethodSignature兩個類,而這兩個類例項化需要花費一些時間;而方法名的對映就在例項化SqlCommand的時候,具體可以看構造方法:

    private final String name;
    private final SqlCommandType type
; public SqlCommand(Configuration configuration,Class<?> mapperInterface,Method method) { final String methodName = method.getName(); final Class<?> declaringClass = method.getDeclaringClass(); MappedStatement ms = resolveMappedStatement(mapperInterface,methodName,declaringClass,configuration); if
(ms == null) { if (method.getAnnotation(Flush.class) != null) { name = null; type = SqlCommandType.FLUSH; } else { throw new BindingException("Invalid bound statement (not found): " + mapperInterface.getName() + "." + methodName); } } else
{ name = ms.getId(); type = ms.getSqlCommandType(); if (type == SqlCommandType.UNKNOWN) { throw new BindingException("Unknown execution method for: " + name); } } } 複製程式碼

首先獲取了方法的名稱和定義此方法的類,一般此類都是xxxMapper類;注此處的declaringClass類和mapperInterface是有區別的,主要是因為此方法可以是父類裡面的方法,而mapperInterface是子類;所以如果定義了父xxxMapper,同樣也能進行對映,所以可以看相關程式碼:

 private MappedStatement resolveMappedStatement(Class<?> mapperInterface,String methodName,Class<?> declaringClass,Configuration configuration) {
      String statementId = mapperInterface.getName() + "." + methodName;
      if (configuration.hasStatement(statementId)) {
        return configuration.getMappedStatement(statementId);
      } else if (mapperInterface.equals(declaringClass)) {
        return null;
      }
      for (Class<?> superInterface : mapperInterface.getInterfaces()) {
        if (declaringClass.isAssignableFrom(superInterface)) {
          MappedStatement ms = resolveMappedStatement(superInterface,configuration);
          if (ms != null) {
            return ms;
          }
        }
      }
      return null;
    }
  }
複製程式碼

可以看到方法名對映的時候並不是隻有名稱,同樣在前面加了介面名稱類似:com
.xx.mapper.XXMapper+方法名,其對應的就是xxMapper.xml中的namespace+statementID;如果可以找到就直接返回configuration中的一個MappedStatement,暫時可以簡單為就是xxMapper.xml的一個標籤塊;如果找不到說明有可能在父類中,可以發現這裡使用遞迴,直到從所有父類中查詢,如果還是找不到返回null;
接著上段程式碼往下看,如果找不到對應的MappedStatement,會檢視方法是否有@Flush註解,如果有指定命令型別為FLUSH,否則就丟擲異常;找到MappedStatement從裡面獲取命令型別,所有型別包括:

public enum SqlCommandType {
  UNKNOWN,INSERT,UPDATE,DELETE,SELECT,FLUSH;
}
複製程式碼

INSERT,SELECT其實也就是我們在xxMapper.xml中定義的標籤;

方法簽名

快取的另一個物件是MethodSignature,直譯就是方法簽名,包含了方法的返回值,引數等,可以看其建構函式:

    public MethodSignature(Configuration configuration,Method method) {
      Type resolvedReturnType = TypeParameterResolver.resolveReturnType(method,mapperInterface);
      if (resolvedReturnType instanceof Class<?>) {
        this.returnType = (Class<?>) resolvedReturnType;
      } else if (resolvedReturnType instanceof ParameterizedType) {
        this.returnType = (Class<?>) ((ParameterizedType) resolvedReturnType).getRawType();
      } else {
        this.returnType = method.getReturnType();
      }
      this.returnsVoid = void.class.equals(this.returnType);
      this.returnsMany = configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray();
      this.returnsCursor = Cursor.class.equals(this.returnType);
      this.mapKey = getMapKey(method);
      this.returnsMap = this.mapKey != null;
      this.rowBoundsIndex = getUniqueParamIndex(method,RowBounds.class);
      this.resultHandlerIndex = getUniqueParamIndex(method,ResultHandler.class);
      this.paramNameResolver = new ParamNameResolver(configuration,method);
    }
複製程式碼

首先是獲取返回值的型別Type,我們在查詢的時候是需要更加具體的型別的,比如是物件型別,基本資料型別,陣列型別,列表型別,Map型別,遊標型別,void型別;所以這裡獲取型別的時候需要Type型別的子介面類一共包括:ParameterizedType,TypeVariable,GenericArrayType,WildcardType這四種分別表示:
ParameterizedType:表示一種引數化的型別,比如Collection;
TypeVariable:表示泛型型別如T;
GenericArrayType:型別變數的陣列型別;
WildcardType:一種萬用字元型別表示式,比如?,? extends Number;
獲取到具體型別之後,根據型別建立了四個標識:returnsMany,returnsMap,returnsVoid,returnsCursor,分別表示:
returnsMany:返回列表或者陣列;
returnsMap:返回一個Map;
returnsVoid:沒有返回值;
returnsCursor:返回一個遊標;
除了以上介紹的幾個引數,還定義了三個引數分別是:RowBounds在所有引數中的位置,ResultHandler引數在所有引數中的位置,以及例項化了一個引數解析類ParamNameResolver用來作為引數轉為sql命令引數;注:RowBounds和ResultHandler是兩個特殊的引數,並不對映到xxMapper.xml中的引數,分別用來處理分頁和對結果進行再處理;

引數對映處理

引數的對映處理主要在ParamNameResolver中處理的,在例項化MethodSignature的同時,初始化了一個ParamNameResolver,建構函式如下:

private final SortedMap<Integer,String> names;

private boolean hasParamAnnotation;

public ParamNameResolver(Configuration config,Method method) {
    final Class<?>[] paramTypes = method.getParameterTypes();
    final Annotation[][] paramAnnotations = method.getParameterAnnotations();
    final SortedMap<Integer,String> map = new TreeMap<Integer,String>();
    int paramCount = paramAnnotations.length;
    // get names from @Param annotations
    for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
      if (isSpecialParameter(paramTypes[paramIndex])) {
        // skip special parameters
        continue;
      }
      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.
        if (config.isUseActualParamName()) {
          name = getActualParamName(method,paramIndex);
        }
        if (name == null) {
          // use the parameter index as the name ("0","1",...)
          // gcode issue #71
          name = String.valueOf(map.size());
        }
      }
      map.put(paramIndex,name);
    }
    names = Collections.unmodifiableSortedMap(map);
  }
複製程式碼

首先獲取了引數的型別,然後獲取引數的註解;接下來遍歷註解,在遍歷的過程中會檢查引數型別是否是RowBounds和ResultHandler,這兩個型別前文說過,是兩個特殊的型別並不用於引數對映,所以這裡過濾掉了,然後獲取註解中的值如@Param("id")中的value="id",如果沒有註解值,會檢查mybatis-config.xml中是否配置了useActualParamName,這是一個開關表示是否使用真實的引數名稱,預設為開啟,如果關閉了開關則使用下標0,1,2...來表示名稱;下面已一個例子來說明一下,比如有如下方法:

public Blog selectBlog3(@Param("id") long id, @Param("author") String author);
複製程式碼

那對應的names為:{0=id,1=author},如果去掉@Param,如下:

public Blog selectBlog3(long id,String author);
複製程式碼

對應的names為:{0=arg0,1=arg1},如果關閉useActualParamName開關:

<setting name="useActualParamName" value="false"/>
複製程式碼

對應的names為:{0=0,1=1};names這裡只是初始化資訊,真正和xxMapper.xml中對映的引數還在ParamNameResolver中的另一個方法中做的處理:

public Object getNamedParams(Object[] args) {
    final int paramCount = names.size();
    if (args == null || paramCount == 0) {
      return null;
    } else if (!hasParamAnnotation && paramCount == 1) {
      return args[names.firstKey()];
    } else {
      final Map<String,Object> param = new ParamMap<Object>();
      int i = 0;
      for (Map.Entry<Integer,String> entry : names.entrySet()) {
        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++;
      }
      return param;
    }
  }
複製程式碼

此方法會遍歷names,在遍歷之前會檢查是否為空和檢查是否只有一個引數,並且沒有給這個引數設定註解,那會直接返回這個引數值,並沒有key,這種情況xxMapper.xml對應的引數名稱其實是不關心的,什麼名稱都可以直接進行對映;如果不是以上兩種情況會遍歷names會分別往一個Map中寫入兩個key值,還是上面的三種情況,經過此方法處理後,值會發生如下變化:

{author=zhaohui, id=158,param1=158,param2=zhaohui}
複製程式碼

以上是有設定註解名稱的情況;

{arg1=zhaohui,arg0=158,param2=zhaohui}
複製程式碼

以上是沒有設定註解名稱的情況,但是開啟了useActualParamName開關;

{0=158, 1=zhaohui,param2=zhaohui}
複製程式碼

以上是沒有設定註解名稱的情況,並且關閉了useActualParamName開關;

有了以上三種情況,所以我們在xxMapper.xml也會有不同的配置方式,下面根據以上三種情況看看在xxMapper.xml中如何配置:
第一種情況,xxMapper.xml可以這樣配置:

    <select id="selectBlog3" parameterType="hashmap" resultType="blog">
        select * from blog where id = #{id} and author=#{author}
    </select>
    <select id="selectBlog3" parameterType="hashmap" resultType="blog">
        select * from blog where id = #{param1} and author=#{param2}
    </select>
複製程式碼

第二種情況,xxMapper.xml可以這樣配置:

    <select id="selectBlog3" parameterType="hashmap" resultType="blog">
        select * from blog where id = #{arg0} and author=#{arg1}
    </select>
    <select id="selectBlog3" parameterType="hashmap" resultType="blog">
        select * from blog where id = #{param1} and author=#{param2}
    </select>
複製程式碼

第三種情況,xxMapper.xml可以這樣配置:

    <select id="selectBlog3" parameterType="hashmap" resultType="blog">
        select * from blog where id = #{0} and author=#{1}
    </select>
    <select id="selectBlog3" parameterType="hashmap" resultType="blog">
        select * from blog where id = #{param1} and author=#{param2}
    </select>
複製程式碼

正是因為Mybatis在初始化引數對映的時候提供了多種key值,更加方便開發者靈活的設定值;雖然提供了多個key值選擇,但個人認為還是設定明確的註解更加規範;

總結

本文重點介紹了SqlCommand和MethodSignature這兩個類的例項化過程,SqlCommand重點介紹了方法名的對映通過介面路徑+方法名的方式和xxMapper.xml中的namespace+statementID進行對映,並且將到了遞迴父類的問題;然後就是方法簽名,通過方法的返回值型別建立了四個標識;最後講了引數的對映問題,Mybatis給開發者提供了多樣的對映key。

示例程式碼地址

Github