
MyBatis源碼解析之基礎子產品—binding
binding未誕生之暗黑時代
在介紹MyBatis的binding之前,咱們先一段代碼:
UserInfoDAO
package com.todobugs.study.dao;
import com.todobugs.study.domain.UserInfo;
import com.todobugs.study.query.UserInfoQuery;
public interface UserInfoDAO {
Long insert(UserInfo userInfo);
/**
* 根據使用者名查找
* @param userName
* @return
*/
UserInfo selectUserInfoByName(String userName);
}
UserInfoDaoImpl
package com.todobugs.study.dao.impl;
import com.todobugs.study.dao.BaseDAO;
import com.todobugs.study.dao.UserInfoDAO;
import com.todobugs.study.domain.UserInfo;
import org.springframework.stereotype.Repository;
@Repository("userInfoDAO")
public class UserInfoDAOImpl extends BaseDAO implements UserInfoDAO {
private static final String SQLMAP_SPACE = "USER_INFO.";
public Long insert(UserInfo userInfo) {
return (Long)getSqlMapClientTemplate().insert(SQLMAP_SPACE + "insert", userInfo);
}
@Override
public UserInfo selectUserInfoByName(String userName) {
return (UserInfo) this.getSqlMapClientTemplate().queryForObject(SQLMAP_SPACE+"getByName", userName);
}
}
上述兩份源碼就是使用ibatis開發的dao,從中可以看出dao實作類其實沒有什麼業務邏輯處理,就是為了綁定namespace 及sql節點。
在ibatis時代,開發者在編寫dao(即現在的mapper)時必須要實作該dao接口,其根本目的隻是指定對應的namespace及操作節點。雖然實作内容很簡單,這給開發者帶來不必要且繁瑣的編碼,且在編譯時并不能發現開發者是否存在異常,隻有在運作時才能發現。
為解決這種操作方式的弊端,在mybatis版本中提供了binding子產品。進而能夠在編譯期就能夠發現問題。同時通過采用jdk動态代理模式,開發者隻需要要編寫對應的接口即可完成持久層的開發工作。即降低工作量,有大大降低出錯機率。
接下來,我們将通過源碼詳細介紹binding的執行邏輯。
架構設計
binding子產品所在包路徑為
org.apache.ibatis.binding
,類關系比較簡單,總共就五個類:
- MapperRegistry:Mapper注冊類
- MapperProxyFactory:Mapper代理工廠類
- MapperProxy:Mapper代理類
- MapperMethod:Mapper執行方法
- BindingException:綁定異常類
其類之間的架構設計關系為:
接下來各類中主要方法依次介紹。
源碼解讀
MapperRegistry
老規矩,先上源碼:
package org.apache.ibatis.binding;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.ibatis.builder.annotation.MapperAnnotationBuilder;
import org.apache.ibatis.io.ResolverUtil;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
public class MapperRegistry {
/** 全局配置類 */
private final Configuration config;
/** 已添加的mapper代理類工廠 */
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();
/** 構造函數 */
public MapperRegistry(Configuration config) {
this.config = config;
}
/** 根據包名添加mapper */
public void addMappers(String packageName) {
//預設superType為Object.class,這樣該包下的所有接口均會被添加到knownMappers中
addMappers(packageName, Object.class);
}
/** 根據指定包名及父類類型添加mapper */
public void addMappers(String packageName, Class<?> superType) {
/** 通過resolverUtil類判斷查詢packageName包下所有比對superType的類型,并添加到一個set類型集合中 */
ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<>();
resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
/** 循環周遊該集合,并将該mapperClass添加到knownMappers中 */
for (Class<?> mapperClass : mapperSet) {
addMapper(mapperClass);
}
}
/**
* 判斷是否為接口,是的話才會生成代理對象
* 後續會在運作時該代理對象會被攔截器進行攔截處理
*/
public <T> void addMapper(Class<T> type) {
/** 1、判斷傳入的type是否是一個接口
* 2、判斷knownMappers是否已經存在,若存在則抛出已存在異常。
* 3、設定是否加載完成辨別,final會根據是否加載完成來差別是否删除該type的設定
* 4、将該接口put到knownMappers中
* 5、調用MapperAnnotationBuilder構造方法,并進行解析。(具體處理邏輯會在builder子產品中展開)
*/
if (type.isInterface()) {
if (hasMapper(type)) {
throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
}
boolean loadCompleted = false;
try {
knownMappers.put(type, new MapperProxyFactory<>(type));
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
/** 擷取mapper代理對象 */
@SuppressWarnings("unchecked")
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
/**判斷knownMappers中是否存在該類型的mapper代理工廠*/
public <T> boolean hasMapper(Class<T> type) {
return knownMappers.containsKey(type);
}
/** 主要用于測試,無需關注 */
public Collection<Class<?>> getMappers() {
return Collections.unmodifiableCollection(knownMappers.keySet());
}
}
在Configuration執行個體化時,會通過如下方式進行執行個體化。
protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
從源碼中可以看出,
MapperRegister
類隻有兩個屬性,七個方法(包含一個構造方法)
- config:該屬性裡面包含各種mybatis的配置資訊,此處不再贅述。
- knownMappers:該屬性存放mapper接口并提供其代理對象(稍後介紹
)。MapperProxyFactory
- MapperRegistry:該構造方法注入config配置資訊。
- addMappers(String packageName):根據包名添加該包下的所有mapper接口類,調用下述重載方法
- addMappers(String packageName, Class<?> superType):重載方法,根據包名及父類類型添加該包下的所有mapper接口類
- getMapper:根據mapper類型及sqlsession擷取對應mapper接口的代理對象。
- hasMapper:根據mapper類型判斷knownMappers中是否已存在,主要用于addMapper時校驗。
- addMapper:根據mapper類型将其添加到knownMappers中,該方法預設被
循環調用,開發者亦可手動調用。addMappers(String packageName, Class<?> superType)
MapperProxyFactory
package org.apache.ibatis.binding;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.ibatis.binding.MapperProxy.MapperMethodInvoker;
import org.apache.ibatis.session.SqlSession;
public class MapperProxyFactory<T> {
/** mapper接口 */
private final Class<T> mapperInterface;
/** method緩存 */
private final Map<Method, MapperMethodInvoker> methodCache = new ConcurrentHashMap<>();
/** 構造方法 */
public MapperProxyFactory(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
/** 擷取mapper接口 */
public Class<T> getMapperInterface() {
return mapperInterface;
}
/** 擷取method緩存 */
public Map<Method, MapperMethodInvoker> getMethodCache() {
return methodCache;
}
/** 建立代理對象 */
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
/** 重載方法建立代理對象 */
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
}
MapperProxyFactory代碼比較簡單,持有mapperInterface,methodCache兩個屬性,一個構造方法(參數為mapper接口),兩個擷取代理對象的newInstance方法:
- MapperProxyFactory(Class mapperInterface) 構造方法在執行MapperRegister#addMapper時添加到knownMappers的過程中進行執行個體化調用
knownMappers.put(type, new MapperProxyFactory<>(type));
- getMethodCache() :擷取methodCache資訊,該methodCache在調用cachedInvoker時進行填充。
- newInstance(SqlSession sqlSession):通過sqlSession建立MappserProxy代理對象執行個體。
- newInstance(MapperProxy mapperProxy):根據mapperProxy代理對象執行個體化代理對象(有點繞😊)
MapperProxy
package org.apache.ibatis.binding;
import java.io.Serializable;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import org.apache.ibatis.reflection.ExceptionUtil;
import org.apache.ibatis.session.SqlSession;
public class MapperProxy<T> implements InvocationHandler, Serializable {
private static final long serialVersionUID = -4724728412955527868L;
private static final int ALLOWED_MODES = MethodHandles.Lookup.PRIVATE | MethodHandles.Lookup.PROTECTED
| MethodHandles.Lookup.PACKAGE | MethodHandles.Lookup.PUBLIC;
private static final Constructor<Lookup> lookupConstructor;
private static final Method privateLookupInMethod;
private final SqlSession sqlSession;
private final Class<T> mapperInterface;
private final Map<Method, MapperMethodInvoker> methodCache;
/** MapperProxy構造方法,被MapperProxyFactory調用用于執行個體化代理對象 */
public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethodInvoker> methodCache) {
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
this.methodCache = methodCache;
}
/** 靜态代碼塊初始化合适的MethodHandler */
static {
Method privateLookupIn;
try {
privateLookupIn = MethodHandles.class.getMethod("privateLookupIn", Class.class, MethodHandles.Lookup.class);
} catch (NoSuchMethodException e) {
privateLookupIn = null;
}
privateLookupInMethod = privateLookupIn;
Constructor<Lookup> lookup = null;
if (privateLookupInMethod == null) {
// JDK 1.8
try {
lookup = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, int.class);
lookup.setAccessible(true);
} catch (NoSuchMethodException e) {
throw new IllegalStateException(
"There is neither 'privateLookupIn(Class, Lookup)' nor 'Lookup(Class, int)' method in java.lang.invoke.MethodHandles.",
e);
} catch (Exception e) {
lookup = null;
}
}
lookupConstructor = lookup;
}
/** 調用(根據method的類型聲明判斷方法調用類型) */
@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 {
return cachedInvoker(proxy, method, args).invoke(proxy, method, args, sqlSession);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
/** 緩存調用 */
private MapperMethodInvoker cachedInvoker(Object proxy, Method method, Object[] args) throws Throwable {
try {
return methodCache.computeIfAbsent(method, m -> {
if (m.isDefault()) {
try {
if (privateLookupInMethod == null) {
return new DefaultMethodInvoker(getMethodHandleJava8(method));
} else {
return new DefaultMethodInvoker(getMethodHandleJava9(method));
}
} catch (IllegalAccessException | InstantiationException | InvocationTargetException
| NoSuchMethodException e) {
throw new RuntimeException(e);
}
} else {
return new PlainMethodInvoker(new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
}
});
} catch (RuntimeException re) {
Throwable cause = re.getCause();
throw cause == null ? re : cause;
}
}
/** jdk1.9下調用 */
private MethodHandle getMethodHandleJava9(Method method)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
final Class<?> declaringClass = method.getDeclaringClass();
return ((Lookup) privateLookupInMethod.invoke(null, declaringClass, MethodHandles.lookup())).findSpecial(
declaringClass, method.getName(), MethodType.methodType(method.getReturnType(), method.getParameterTypes()),
declaringClass);
}
/** jdk1.8下調用 */
private MethodHandle getMethodHandleJava8(Method method)
throws IllegalAccessException, InstantiationException, InvocationTargetException {
final Class<?> declaringClass = method.getDeclaringClass();
return lookupConstructor.newInstance(declaringClass, ALLOWED_MODES).unreflectSpecial(method, declaringClass);
}
/** 内部接口MapperMethodInvoker */
interface MapperMethodInvoker {
Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable;
}
/** MapperMethodInvoker接口PlainMethodInvoker實作 */
private static class PlainMethodInvoker implements MapperMethodInvoker {
private final MapperMethod mapperMethod;
public PlainMethodInvoker(MapperMethod mapperMethod) {
super();
this.mapperMethod = mapperMethod;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable {
/** 調用MapperMethod中的excute方法 */
return mapperMethod.execute(sqlSession, args);
}
}
/** MapperMethodInvoker接口 DefaultMethodInvoker 實作 */
private static class DefaultMethodInvoker implements MapperMethodInvoker {
private final MethodHandle methodHandle;
public DefaultMethodInvoker(MethodHandle methodHandle) {
super();
this.methodHandle = methodHandle;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable {
return methodHandle.bindTo(proxy).invokeWithArguments(args);
}
}
}
MapperProxy代碼較多,但主要功能還是比較清晰簡單
- 首先因項目運作環境的jdk可能不同,在啟動時會通過靜态代碼塊中判斷采用哪種形式的MethodHandler,在jdk1.8環境下,會使用Constructor 方式,後續對應調用的方法為
,其他環境下采用Method方式,調用方法為getMethodHandleJava8(Method method)
getMethodHandleJava9(Method method)
- 定義内部接口
,其唯一接口方法為:MapperMethodInvoker
Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable;
該接口有兩個私有實作類:PlainMethodInvoker,DefaultMethodInvoker
- PlainMethodInvoker 類通過MyBatis自定義的MapperMethod來執行對應的sqlSession 請求
//通過構造方法注入 private final MapperMethod mapperMethod; @Override public Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable { return mapperMethod.execute(sqlSession, args); }
- DefaultMethodInvoker 類采用jdk自帶的MethodHandler方式,通過綁定代理類來調用sqlSession請求。
//通過構造方法注入 private final MethodHandle methodHandle; @Override public Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable { return methodHandle.bindTo(proxy).invokeWithArguments(args); }
- MapperProxy 實作InvocationHandler接口中的invoke方法:
- 首先判斷傳入的method聲明類型是否為Object.class,若是則直接調用
method.invoke(this, args);
- 否則調用MapperProxy私有方法
cachedInvoker(Object proxy, Method method, Object[] args)
- 首先判斷傳入的method聲明類型是否為Object.class,若是則直接調用
- cachedInvoker方法:
- 首先将傳入method的加入到methodCache中(如果不存在時加入)。
- 根據該方法是否是isDefault類型執行不同的邏輯。
- 如果isDefault == true,則調用DefaultMethodInvoker(根據privateLookupInMethod是否為null來決定使用getMethodHandleJava8還是getMethodHandleJava9)
- 如果isDefault == false,則調用PlainMethodInvoker,關于MapperMethod介紹,請繼續閱讀
return new PlainMethodInvoker(new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
MapperMethod
MapperMethod
類除了定義相關方法外,還定義了兩個内部類:
SqlCommand
和
MethodSignature
。
SqlCommand
類
該類定義兩個屬性:String類型的name、
SqlCommandType
類型的type及對應的get方法。
SqlCommandType
為枚舉類,其值為UNKNOWN, INSERT, UPDATE, DELETE, SELECT, FLUSH。
SqlCommand
還提供了一個有參構造方法,如下:
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);
/** 判斷ms是否為null
* 1、如果不為null,則擷取對應的sql id 和執行類型并指派給name、type
* 2、如果為null,則再次判斷執行方法上是否有注解Flush,如果有則name設定為null,type設定為FLUSH;否則抛出BindingException
*/
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);
}
}
}
該構造方法主要目的是根據configuration、mapperInterface、method參數擷取對應的name、type值。以用于MapperMethod中excute方法的邏輯處理。構造方法中調用了SqlCommand定義的私有方法,方法的具體邏輯見如下源碼注釋。
/**
* 1、根據接口全路徑名及方法名組裝成statementId
* 2、判斷configuration 中是否存在該mappedStatement,若存在則直接傳回
* 3、如果不存在則從父類接口中繼續查找,如果找不到則傳回null
* 4、如果入參路徑就是方法所在的路徑,則直接傳回null
*/
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, methodName,
declaringClass, configuration);
if (ms != null) {
return ms;
}
}
}
return null;
}
MethodSignature
MethodSignature類定義了method相關屬性,具體内容參看如下源碼。
public static class MethodSignature {
/** 是否傳回多值 */
private final boolean returnsMany;
/** 是否傳回map */
private final boolean returnsMap;
/** 是否傳回void類型 */
private final boolean returnsVoid;
/** 是否傳回cursor */
private final boolean returnsCursor;
/** 是否傳回optional */
private final boolean returnsOptional;
/** 傳回類型 */
private final Class<?> returnType;
/** map主鍵 */
private final String mapKey;
/** 傳回結果的handler索引 */
private final Integer resultHandlerIndex;
/** 傳回rowBound索引 */
private final Integer rowBoundsIndex;
/** 參數名稱解析器 */
private final ParamNameResolver paramNameResolver;
/** 構造函數,主要對屬性進行指派 */
public MethodSignature(Configuration configuration, Class<?> mapperInterface, 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.returnsOptional = Optional.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);
}
// boolean及get方法略
private Integer getUniqueParamIndex(Method method, Class<?> paramType) {
Integer index = null;
final Class<?>[] argTypes = method.getParameterTypes();
for (int i = 0; i < argTypes.length; i++) {
if (paramType.isAssignableFrom(argTypes[i])) {
if (index == null) {
index = i;
} else {
throw new BindingException(method.getName() + " cannot have multiple " + paramType.getSimpleName() + " parameters");
}
}
}
return index;
}
/** 判斷method的傳回類型是否有注解主鍵,有則傳回該主鍵value,沒有傳回null */
private String getMapKey(Method method) {
String mapKey = null;
if (Map.class.isAssignableFrom(method.getReturnType())) {
final MapKey mapKeyAnnotation = method.getAnnotation(MapKey.class);
if (mapKeyAnnotation != null) {
mapKey = mapKeyAnnotation.value();
}
}
return mapKey;
}
}
介紹完MapperMethod的兩個内部類,我們回過了頭來看下其自己的源碼結構。
MapperMethod有兩個屬性 command及method,這兩個屬性是在MapperMethod構造方法中通過調用各自類型的構造方法進行初始化,源碼如下:
private final SqlCommand command;
private final MethodSignature method;
public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
this.command = new SqlCommand(config, mapperInterface, method);
this.method = new MethodSignature(config, mapperInterface, method);
}
MapperMethod核心方法為execute,其邏輯如下:
/** MapperMethod 核心執行邏輯根據command類型:
* insert、update、delete 分别調用對應的執行指令,同時調用rowCountResult 傳回受影響的條數
* select操作,其執行會根據是否有結果處理器及傳回資料類型調用不同的方法
*/
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());
}
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;
}
private Object rowCountResult(int rowCount) {
final Object result;
if (method.returnsVoid()) {
result = null;
} else if (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType())) {
result = rowCount;
} else if (Long.class.equals(method.getReturnType()) || Long.TYPE.equals(method.getReturnType())) {
result = (long)rowCount;
} else if (Boolean.class.equals(method.getReturnType()) || Boolean.TYPE.equals(method.getReturnType())) {
result = rowCount > 0;
} else {
throw new BindingException("Mapper method '" + command.getName() + "' has an unsupported return type: " + method.getReturnType());
}
return result;
}
private void executeWithResultHandler(SqlSession sqlSession, Object[] args) {
MappedStatement ms = sqlSession.getConfiguration().getMappedStatement(command.getName());
if (!StatementType.CALLABLE.equals(ms.getStatementType())
&& void.class.equals(ms.getResultMaps().get(0).getType())) {
throw new BindingException("method " + command.getName()
+ " needs either a @ResultMap annotation, a @ResultType annotation,"
+ " or a resultType attribute in XML so a ResultHandler can be used as a parameter.");
}
Object param = method.convertArgsToSqlCommandParam(args);
if (method.hasRowBounds()) {
RowBounds rowBounds = method.extractRowBounds(args);
sqlSession.select(command.getName(), param, rowBounds, method.extractResultHandler(args));
} else {
sqlSession.select(command.getName(), param, method.extractResultHandler(args));
}
}
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.selectList(command.getName(), param, rowBounds);
} else {
result = sqlSession.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;
}
private <T> Cursor<T> executeForCursor(SqlSession sqlSession, Object[] args) {
Cursor<T> result;
Object param = method.convertArgsToSqlCommandParam(args);
if (method.hasRowBounds()) {
RowBounds rowBounds = method.extractRowBounds(args);
result = sqlSession.selectCursor(command.getName(), param, rowBounds);
} else {
result = sqlSession.selectCursor(command.getName(), param);
}
return result;
}
private <E> Object convertToDeclaredCollection(Configuration config, List<E> list) {
Object collection = config.getObjectFactory().create(method.getReturnType());
MetaObject metaObject = config.newMetaObject(collection);
metaObject.addAll(list);
return collection;
}
@SuppressWarnings("unchecked")
private <E> Object convertToArray(List<E> list) {
Class<?> arrayComponentType = method.getReturnType().getComponentType();
Object array = Array.newInstance(arrayComponentType, list.size());
if (arrayComponentType.isPrimitive()) {
for (int i = 0; i < list.size(); i++) {
Array.set(array, i, list.get(i));
}
return array;
} else {
return list.toArray((E[])array);
}
}
private <K, V> Map<K, V> executeForMap(SqlSession sqlSession, Object[] args) {
Map<K, V> result;
Object param = method.convertArgsToSqlCommandParam(args);
if (method.hasRowBounds()) {
RowBounds rowBounds = method.extractRowBounds(args);
result = sqlSession.selectMap(command.getName(), param, method.getMapKey(), rowBounds);
} else {
result = sqlSession.selectMap(command.getName(), param, method.getMapKey());
}
return result;
}
如上就是MapperMethod類檔案中主要的邏輯介紹。MapperMethod會在執行個體化PlainMethodInvoker時進行執行個體化。
BindingException
綁定異常處理類,在Mybatis的綁定處理過程中,若出現異常情況則會抛出該類型的異常。BindingException本質上還是繼承于RuntimeException類。
public class BindingException extends PersistenceException {
private static final long serialVersionUID = 4300802238789381562L;
public BindingException() {
super();
}
public BindingException(String message) {
super(message);
}
public BindingException(String message, Throwable cause) {
super(message, cause);
}
public BindingException(Throwable cause) {
super(cause);
}
}
總結
雖然Binding子產品代碼不多,但在設計層面還是下足了功夫,比如在Mapper采用JDK動态代理模式,在Mapper注冊時采用工廠模式等。
關于MyBatis的Binding子產品介紹至此告一段落。感謝垂閱,如有不妥之處請多多指教~
微觀世界,達觀人生。
做一名踏實的coder !
歡迎關注我的個人微信公衆号 :todobugs ~