在使用Mybatis的時候大家可能都有一個疑問,為什么只寫Mapper接口就能操作數(shù)據(jù)庫?
它的主要實現(xiàn)思想是:使用動態(tài)代理生成實現(xiàn)類,然后配合xml的映射文件中的SQL語句來實現(xiàn)對數(shù)據(jù)庫的訪問。
Mybatis編程模型
Mybatis是在iBatis上演變而來ORM框架,所以Mybatis最終會將代碼轉(zhuǎn)換成iBatis編程模型,而 Mybatis 代理階段主要是將面向接口編程模型,通過動態(tài)代理轉(zhuǎn)換成ibatis編程模型。
我們不直接使用iBatis編程模型的原因是為了解耦,從下面的兩種示例我們可以看出,iBatis編程模型和配置文件耦合很嚴重。
面向接口編程模型
@Test
// 面向接口編程模型
public void quickStart() throws Exception {
// 2.獲取sqlSession
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
initH2dbMybatis(sqlSession);
// 3.獲取對應(yīng)mapper
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
JdkProxySourceClassUtil.writeClassToDisk(mapper.getClass().getSimpleName(), mapper.getClass());
// 4.執(zhí)行查詢語句并返回結(jié)果
Person person = mapper.selectByPrimaryKey(1L);
System.out.println(person.toString());
}
}
ibatis編程模型
@Test
// ibatis編程模型
public void quickStartIBatis() throws Exception {
// 2.獲取sqlSession
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
initH2dbMybatis(sqlSession);
// ibatis編程模型(與配置文件耦合嚴重)
Person person = sqlSession.selectOne("com.xiaolyuh.domain.mapper.PersonMapper.selectByPrimaryKey", 1L);
System.out.println(person.toString());
}
}
代理模塊核心類
- MapperRegistry:Mapper接口動態(tài)代理工廠(MapperProxyFactory)的注冊中心
- MapperProxyFactory:Mapper接口對應(yīng)的動態(tài)代理工廠類。Mapper接口和MapperProxyFactory工廠類是一一對應(yīng)關(guān)系
- MapperProxy:Mapper接口的增強器,它實現(xiàn)了
InvocationHandler接口,通過該增強的invoke方法實現(xiàn)了對數(shù)據(jù)庫的訪問 - MapperMethod:對insert, update, delete, select, flush節(jié)點方法的包裝類,它通過
sqlSession來完成了對數(shù)據(jù)庫的操作

代理初始化
加載Mapper接口到內(nèi)存
在Mybatis 源碼(二)中我們會發(fā)現(xiàn)當(dāng)配置文件解析完成的最后一步是調(diào)用org.apache.ibatis.builder.xml.XMLMapperBuilder#bindMapperForNamespace方法。該方法的主要作用是:根據(jù) namespace 屬性將Mapper接口的動態(tài)代理工廠(MapperProxyFactory)注冊到 MapperRegistry 中。源碼如下:
private void bindMapperForNamespace() {
// 獲取namespace屬性(對應(yīng)Mapper接口的全類名)
String namespace = builderAssistant.getCurrentNamespace();
if (namespace != null) {
Class<?> boundType = null;
try {
boundType = Resources.classForName(namespace);
} catch (ClassNotFoundException e) {
//ignore, bound type is not required
}
if (boundType != null) {
// 防止重復(fù)加載
if (!configuration.hasMapper(boundType)) {
// Spring may not know the real resource name so we set a flag
// to prevent loading again this resource from the mapper interface
// look at MapperAnnotationBuilder#loadXmlResource
configuration.addLoadedResource("namespace:" + namespace);
// 將Mapper接口的動態(tài)代理工廠注冊到 MapperRegistry 中
configuration.addMapper(boundType);
}
}
}
}
- 讀取namespace屬性,獲取Mapper接口的全類名
- 根據(jù)全類名將Mapper接口加載到內(nèi)存
- 判斷是否重復(fù)加載Mapper接口
- 調(diào)用Mybatis 配置類(configuration)的addMapper方法,完成后續(xù)步驟
注冊代理工廠類
org.apache.ibatis.session.Configuration#addMapper該方法直接回去調(diào)用org.apache.ibatis.binding.MapperRegistry#addMapper方法完成注冊。
public <T> void addMapper(Class<T> type) {
// 必須是接口
if (type.isInterface()) {
if (hasMapper(type)) {
// 防止重復(fù)注冊
throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
}
boolean loadCompleted = false;
try {
// 根據(jù)接口類,創(chuàng)建MapperProxyFactory代理工廠類
knownMappers.put(type, new MapperProxyFactory<>(type));
// It's important that the type is added before the parser is run
// otherwise the binding may automatically be attempted by the
// mapper parser. If the type is already known, it won't try.
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
// 如果加載出現(xiàn)異常需要移除對應(yīng)Mapper
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
- 判斷加載類型是否是接口
- 重復(fù)注冊校驗,如果校驗不通拋出
BindingException異常 - 根據(jù)接口類,創(chuàng)建MapperProxyFactory代理工廠類
- 如果加載出現(xiàn)異常需要移除對應(yīng)Mapper
獲取代理對象
在Mybatis 源碼(一)的快速開始中有如下代碼,通過 sqlSession獲取Mapper的代理對象:
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
getMapper 獲取代理對象
sqlSession.getMapper(PersonMapper.class)最終調(diào)用的是org.apache.ibatis.binding.MapperRegistry#getMapper方法,最后返回的是PersonMapper接口的代理對象,源碼如下:
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
// 根據(jù)類型獲取對應(yīng)的代理工廠
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
// 根據(jù)工廠類新建一個代理對象,并返回
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
- 根據(jù)類型獲取對應(yīng)的代理工廠
- 根據(jù)工廠類新建一個代理對象,并返回
newInstance 創(chuàng)建代理對象
每一個Mapper接口對應(yīng)一個MapperProxyFactory工廠類。
MapperProxyFactory通過JDK動態(tài)代理創(chuàng)建代理對象,Mapper接口的代理對象是方法級別,所以每次訪問數(shù)據(jù)庫都需要新創(chuàng)建代理對象。源碼如下:
protected T newInstance(MapperProxy<T> mapperProxy) {
// 使用JDK動態(tài)代理生成代理實例
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
// Mapper的增強器
final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
- 先獲取Mapper對應(yīng)增強器(MapperProxy)
- 根據(jù)增強器使用JDK動態(tài)代理產(chǎn)生代理對象
代理類的反編譯結(jié)果
import com.sun.proxy..Proxy8;
import com.xiaolyuh.domain.model.Person;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
public final class $Proxy8 extends Proxy implements Proxy8 {
private static Method m3;
...
public $Proxy8(InvocationHandler var1) throws {
super(var1);
}
...
public final Person selectByPrimaryKey(Long var1) throws {
try {
return (Person)super.h.invoke(this, m3, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
static {
try {
m3 = Class.forName("com.sun.proxy.$Proxy8").getMethod("selectByPrimaryKey", Class.forName("java.lang.Long"));
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}
從代理類的反編譯結(jié)果來看,都是直接調(diào)用增強器的invoke方法,進而實現(xiàn)對數(shù)據(jù)庫的訪問。
執(zhí)行代理
通過上訴反編譯代理對象,我們可以發(fā)現(xiàn)所有對數(shù)據(jù)庫的訪問都是在增強器org.apache.ibatis.binding.MapperProxy#invoke中實現(xiàn)的。
執(zhí)行增強器 MapperProxy
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
// 如果是Object本身的方法不增強
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對象
final MapperMethod mapperMethod = cachedMapperMethod(method);
// 執(zhí)行MapperMethod
return mapperMethod.execute(sqlSession, args);
}
- 如果是Object本身的方法不增強
- 判斷是否是默認方法
- 從緩存中獲取MapperMethod對象
- 執(zhí)行MapperMethod
模型轉(zhuǎn)換 MapperMethod
MapperMethod封裝了Mapper接口中對應(yīng)方法的信息(MethodSignature),以及對應(yīng)的sql語句的信息(SqlCommand);它是mapper接口與映射配置文件中sql語句的橋梁; MapperMethod對象不記錄任何狀態(tài)信息,所以它可以在多個代理對象之間共享;
- SqlCommand : 從configuration中獲取方法的命名空間.方法名以及SQL語句的類型;
- MethodSignature:封裝mapper接口方法的相關(guān)信息(入?yún)?,返回類型)?/li>
- ParamNameResolver: 解析mapper接口方法中的入?yún)ⅲ?/li>
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
// 根據(jù)SQL類型,調(diào)用不同方法。
// 這里我們可以看出,操作數(shù)據(jù)庫都是通過 sqlSession 來實現(xiàn)的
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:
// 根據(jù)方法返回值類型來確認調(diào)用sqlSession的哪個方法
// 無返回值或者有結(jié)果處理器
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
}
// 返回值是否為集合類型或數(shù)組
else if (method.returnsMany()) {
result = executeForMany(sqlSession, args);
}
// 返回值是否為Map
else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
}
// 返回值是否為游標(biāo)類型
else if (method.returnsCursor()) {
result = executeForCursor(sqlSession, args);
}
// 查詢單條記錄
else {
// 參數(shù)解析
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 <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
List<E> result;
// 將方法參數(shù)轉(zhuǎn)換成SqlCommand參數(shù)
Object param = method.convertArgsToSqlCommandParam(args);
if (method.hasRowBounds()) {
// 獲取分頁參數(shù)
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;
}
在execute方法中完成了面向接口編程模型到iBatis編程模型的轉(zhuǎn)換,轉(zhuǎn)換過程如下:
- 通過
MapperMethod.SqlCommand. type+MapperMethod.MethodSignature.returnType來確定需要調(diào)用SqlSession中的那個方法 - 通過
MapperMethod.SqlCommand. name來找到需要執(zhí)行方法的全類名 - 通過
MapperMethod.MethodSignature.paramNameResolver來轉(zhuǎn)換需要傳遞的參數(shù)
SqlSession
在Mybatis中SqlSession相當(dāng)于一個門面,所有對數(shù)據(jù)庫的操作都需要通過SqlSession接口,SqlSession中定義了所有對數(shù)據(jù)庫的操作方法,如數(shù)據(jù)庫讀寫命令、獲取映射器、管理事務(wù)等,也是Mybatis中為數(shù)不多的有注釋的類。

流程圖

總結(jié)
通過上面的源碼解析,可以發(fā)現(xiàn)Mybatis面向接口編程是通過JDK動態(tài)代理模式來實現(xiàn)的。主要執(zhí)行流程是:
- 在映射文件初始化完成后,將對應(yīng)的Mapper接口的代理工廠類
MapperProxyFactory注冊到MapperRegistry - 每次操作數(shù)據(jù)庫時,
sqlSession通過MapperProxyFactory獲取Mapper接口的代理類 - 代理類通過增強器
MapperProxy調(diào)用XML映射文件中SQL節(jié)點的封裝類MapperMethod - 通過
MapperMethod將Mybatis 面向接口的編程模型轉(zhuǎn)換成iBatis編程模型(SqlSession模型) - 通過
SqlSession完成對數(shù)據(jù)庫的操作
示例源碼
https://github.com/wyh-spring-ecosystem-student/spring-boot-student/tree/releases
spring-boot-student-mybatis工程