這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)Mybatis代理模塊有哪些以及如何執(zhí)行,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比西疇網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式西疇網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋西疇地區(qū)。費(fèi)用合理售后完善,十載實(shí)體公司更值得信賴。
在使用Mybatis的時(shí)候大家可能都有一個(gè)疑問,為什么只寫Mapper接口就能操作數(shù)據(jù)庫?
它的主要實(shí)現(xiàn)思想是:使用動態(tài)代理生成實(shí)現(xiàn)類,然后配合xml的映射文件中的SQL語句來實(shí)現(xiàn)對數(shù)據(jù)庫的訪問。
Mybatis是在iBatis上演變而來ORM框架,所以Mybatis最終會將代碼轉(zhuǎn)換成iBatis編程模型,而 Mybatis 代理階段主要是將面向接口編程模型,通過動態(tài)代理轉(zhuǎn)換成ibatis編程模型。
我們不直接使用iBatis編程模型的原因是為了解耦,從下面的兩種示例我們可以看出,iBatis編程模型和配置文件耦合很嚴(yán)重。
@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());
}
}@Test
// ibatis編程模型
public void quickStartIBatis() throws Exception {
// 2.獲取sqlSession
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
initH2dbMybatis(sqlSession);
// ibatis編程模型(與配置文件耦合嚴(yán)重)
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接口的增強(qiáng)器,它實(shí)現(xiàn)了InvocationHandler接口,通過該增強(qiáng)的invoke方法實(shí)現(xiàn)了對數(shù)據(jù)庫的訪問
MapperMethod:對insert, update, delete, select, flush節(jié)點(diǎn)方法的包裝類,它通過sqlSession來完成了對數(shù)據(jù)庫的操作

在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ù)注冊校驗(yàn),如果校驗(yàn)不通拋出BindingException異常
根據(jù)接口類,創(chuàng)建MapperProxyFactory代理工廠類
如果加載出現(xiàn)異常需要移除對應(yīng)Mapper
在Mybatis 源碼(一)的快速開始中有如下代碼,通過 sqlSession獲取Mapper的代理對象:
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
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ù)工廠類新建一個(gè)代理對象,并返回
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}根據(jù)類型獲取對應(yīng)的代理工廠
根據(jù)工廠類新建一個(gè)代理對象,并返回
每一個(gè)Mapper接口對應(yīng)一個(gè)MapperProxyFactory工廠類。 MapperProxyFactory通過JDK動態(tài)代理創(chuàng)建代理對象,Mapper接口的代理對象是方法級別,所以每次訪問數(shù)據(jù)庫都需要新創(chuàng)建代理對象。源碼如下:
protected T newInstance(MapperProxy<T> mapperProxy) {
// 使用JDK動態(tài)代理生成代理實(shí)例
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
// Mapper的增強(qiáng)器
final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}先獲取Mapper對應(yīng)增強(qiáng)器(MapperProxy)
根據(jù)增強(qiáng)器使用JDK動態(tài)代理產(chǎn)生代理對象
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)用增強(qiáng)器的invoke方法,進(jìn)而實(shí)現(xiàn)對數(shù)據(jù)庫的訪問。
通過上訴反編譯代理對象,我們可以發(fā)現(xiàn)所有對數(shù)據(jù)庫的訪問都是在增強(qiáng)器org.apache.ibatis.binding.MapperProxy#invoke中實(shí)現(xiàn)的。
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
// 如果是Object本身的方法不增強(qiáng)
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
}
// 判斷是否是默認(rèn)方法
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本身的方法不增強(qiáng)
判斷是否是默認(rèn)方法
從緩存中獲取MapperMethod對象
執(zhí)行MapperMethod
MapperMethod封裝了Mapper接口中對應(yīng)方法的信息(MethodSignature),以及對應(yīng)的sql語句的信息(SqlCommand);它是mapper接口與映射配置文件中sql語句的橋梁; MapperMethod對象不記錄任何狀態(tài)信息,所以它可以在多個(gè)代理對象之間共享;
SqlCommand : 從configuration中獲取方法的命名空間.方法名以及SQL語句的類型;
MethodSignature:封裝mapper接口方法的相關(guān)信息(入?yún)ⅲ祷仡愋停?/p>
ParamNameResolver: 解析mapper接口方法中的入?yún)ⅲ?/p>
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
// 根據(jù)SQL類型,調(diào)用不同方法。
// 這里我們可以看出,操作數(shù)據(jù)庫都是通過 sqlSession 來實(shí)現(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ù)方法返回值類型來確認(rèn)調(diào)用sqlSession的哪個(gè)方法
// 無返回值或者有結(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中的那個(gè)方法
通過MapperMethod.SqlCommand. name來找到需要執(zhí)行方法的全類名
通過MapperMethod.MethodSignature.paramNameResolver來轉(zhuǎn)換需要傳遞的參數(shù)
在Mybatis中SqlSession相當(dāng)于一個(gè)門面,所有對數(shù)據(jù)庫的操作都需要通過SqlSession接口,SqlSession中定義了所有對數(shù)據(jù)庫的操作方法,如數(shù)據(jù)庫讀寫命令、獲取映射器、管理事務(wù)等,也是Mybatis中為數(shù)不多的有注釋的類。


通過上面的源碼解析,可以發(fā)現(xiàn)Mybatis面向接口編程是通過JDK動態(tài)代理模式來實(shí)現(xiàn)的。主要執(zhí)行流程是:
在映射文件初始化完成后,將對應(yīng)的Mapper接口的代理工廠類MapperProxyFactory注冊到MapperRegistry
每次操作數(shù)據(jù)庫時(shí),sqlSession通過MapperProxyFactory獲取Mapper接口的代理類
代理類通過增強(qiáng)器MapperProxy調(diào)用XML映射文件中SQL節(jié)點(diǎn)的封裝類MapperMethod
通過MapperMethod將Mybatis 面向接口的編程模型轉(zhuǎn)換成iBatis編程模型(SqlSession模型)
通過SqlSession完成對數(shù)據(jù)庫的操作
上述就是小編為大家分享的Mybatis代理模塊有哪些以及如何執(zhí)行了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
文章題目:Mybatis代理模塊有哪些以及如何執(zhí)行
鏈接地址:http://chinadenli.net/article24/iicoce.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供商城網(wǎng)站、建站公司、網(wǎng)頁設(shè)計(jì)公司、企業(yè)建站、外貿(mào)建站、手機(jī)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)