MethodSignature分析
MethodSignature為MapperMethod類提供了三個作用,獲取待執行方法中的參數和@Param注解標注的參數名,獲取標注有@MapKey的參數(@Mapkey作用在后續會講到),方法的返回類型,獲取SELECT操作時必要的標志位。以下是MethodSignature的所有屬性。
- private final boolean returnsMany;//是否多值查詢
- private final boolean returnsMap;//是否map查詢
- private final boolean returnsVoid;//是否void查詢
- private final boolean returnsCursor;//是否游標查詢
- private final Class<?> returnType; //返回類型
- private final String mapKey;//獲取mapKey的值
- private final Integer resultHandlerIndex;
- private final Integer rowBoundsIndex;
- private final ParamNameResolver paramNameResolver; //參數解析器
觀察下列的代碼,構造器首先獲取返回類型,這個值通過類型參數解析器來獲取入參mapperInterface本身及所有的父類和所有的接口來查找所要返回的類型,Mybatis提供了三種類型實現ParameterizedType,TypeVariable,GenericArrayType。通過返回的類型值來判定后續的SElECT將要做哪種查詢,void查詢,Map查詢,游標查詢,多值查詢,這里就會給相關的屬性進行打標,在mapperMethod執行exeute()方法時便會進行判斷。構造器還會檢查待執行的Mapper方法是否標注有@Mapkey的注解,如果有這意味着返回的結果類型是一個Map。
1 public MethodSignature(Configuration configuration, Class<?> mapperInterface, Method method) { 2 //解析返回的類型 ParameterizedType,TypeVariable,GenericArrayType 3 Type resolvedReturnType = TypeParameterResolver.resolveReturnType(method, mapperInterface); 4 if (resolvedReturnType instanceof Class<?>) { 5 this.returnType = (Class<?>) resolvedReturnType; 6 } else if (resolvedReturnType instanceof ParameterizedType) { 7 this.returnType = (Class<?>) ((ParameterizedType) resolvedReturnType).getRawType(); 8 } else { 9 this.returnType = method.getReturnType(); 10 } 11 this.returnsVoid = void.class.equals(this.returnType); 12 //是否是集合或者數組類型 13 this.returnsMany = configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray(); 14 //判斷是否是游標類型 15 this.returnsCursor = Cursor.class.equals(this.returnType); 16 //獲取MapKey注解 17 this.mapKey = getMapKey(method); 18 //判斷mapkey是否不為NULL 19 this.returnsMap = this.mapKey != null; 20 this.rowBoundsIndex = getUniqueParamIndex(method, RowBounds.class); 21 this.resultHandlerIndex = getUniqueParamIndex(method, ResultHandler.class); 22 //初始化參數名解析器 23 this.paramNameResolver = new ParamNameResolver(configuration, method); 24 }