binding包下的核心類
MapperMethod
主要功能:把crud的方法委托給SqlSession.
MapperProxy
主要功能:mapperInterface的crud方法實(shí)際執(zhí)行入口,把具體的功能委托給MapperMethod
MapperProxyFactory
主要功能:生成proxy代理
MapperRegistry
主要功能:getMapper,addMapper
我們平時(shí)使用mybatis的時(shí)候是用的一個(gè)接口,OrderMapper,這個(gè)orderMapper接口為什么能實(shí)現(xiàn)相關(guān)的功能呢?
原因就是mybatis會(huì)把這個(gè)接口生成一個(gè)動(dòng)態(tài)代理類,我們?nèi)ybatis的binding包下面看看,就發(fā)現(xiàn)有個(gè)MapperProxy代理類,這個(gè)MapperProxy繼承了InvocationHandler.
這個(gè)包下面的類的設(shè)計(jì)挺棒的.下面邏輯了核心的四個(gè)類.MapperProxy并沒有直接的暴露出去,Mybatis封裝了一個(gè)MapperRegistry,當(dāng)getMapper被調(diào)用的時(shí)候,先獲取MapperProxyFactory,因?yàn)殡m然現(xiàn)在使用的是MapperProxy,如果后面的實(shí)現(xiàn)發(fā)生了變化呢?為了把這個(gè)變化點(diǎn)封裝出來,Mybatis用了Factory模式.
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 {
//MapperRegistry -> MapperProxyFactory
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
public T newInstance(SqlSession sqlSession) {
//封裝成MapperProxy MapperProxy實(shí)現(xiàn)了InvocationHandler
final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
//remove redundant t
return newInstance(mapperProxy);
}
這里生成了mapper接口的代理類,用的的jdk的動(dòng)態(tài)代理.
protected T newInstance(MapperProxy<T> mapperProxy) {
//用proxy生成代理對(duì)象.
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
}
我們知道動(dòng)態(tài)代理的核心調(diào)用是invoke方法,我們進(jìn)入到這個(gè)invoke方法.這里的核心就是把事情委托給MapperMethod了.然后MapperMethod跟再下一層SqlSession進(jìn)行交互的sql執(zhí)行類進(jìn)行交互.每一層代碼都很清晰,每個(gè)類都有自己的清晰的職責(zé).
@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 (method.isDefault()) {
if (privateLookupInMethod == null) {
return invokeDefaultMethodJava8(proxy, method, args);
} else {
return invokeDefaultMethodJava9(proxy, method, args);
}
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
//MapperMethod負(fù)責(zé)執(zhí)行sql
final MapperMethod mapperMethod = cachedMapperMethod(method);
//switch case update or select .....
return mapperMethod.execute(sqlSession, args);
}
到這里,就一目了然了吧.這里做個(gè)簡(jiǎn)單的邏輯判斷,然后就交給SqlSession,然后接受到SqlSession返回的結(jié)果.
//最終執(zhí)行sql的地方
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;
}