溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Mybatis代理模塊有哪些以及如何執(zhí)行

發(fā)布時間:2021-10-09 15:23:38 來源:億速云 閱讀:112 作者:柒染 欄目:大數(shù)據(jù)

這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)Mybatis代理模塊有哪些以及如何執(zhí)行,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

在使用Mybatis的時候大家可能都有一個疑問,為什么只寫Mapper接口就能操作數(shù)據(jù)庫?

它的主要實(shí)現(xiàn)思想是:使用動態(tài)代理生成實(shí)現(xiàn)類,然后配合xml的映射文件中的SQL語句來實(shí)現(xiàn)對數(shù)據(jù)庫的訪問。

Mybatis編程模型

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());
    }
}

ibatis編程模型

@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代理模塊有哪些以及如何執(zhí)行

代理初始化

加載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);
      }
    }
  }
}
  1. 讀取namespace屬性,獲取Mapper接口的全類名

  2. 根據(jù)全類名將Mapper接口加載到內(nèi)存

  3. 判斷是否重復(fù)加載Mapper接口

  4. 調(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);
      }
    }
  }
}
  1. 判斷加載類型是否是接口

  2. 重復(fù)注冊校驗(yàn),如果校驗(yàn)不通拋出BindingException異常

  3. 根據(jù)接口類,創(chuàng)建MapperProxyFactory代理工廠類

  4. 如果加載出現(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);
  }
}
  1. 根據(jù)類型獲取對應(yīng)的代理工廠

  2. 根據(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)代理生成代理實(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);
}
  1. 先獲取Mapper對應(yīng)增強(qiáng)器(MapperProxy)

  2. 根據(jù)增強(qiáng)器使用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)用增強(qiáng)器的invoke方法,進(jìn)而實(shí)現(xiàn)對數(shù)據(jù)庫的訪問。

執(zhí)行代理

通過上訴反編譯代理對象,我們可以發(fā)現(xiàn)所有對數(shù)據(jù)庫的訪問都是在增強(qiáng)器org.apache.ibatis.binding.MapperProxy#invoke中實(shí)現(xiàn)的。

執(zhí)行增強(qiáng)器 MapperProxy

@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);
}
  1. 如果是Object本身的方法不增強(qiáng)

  2. 判斷是否是默認(rèn)方法

  3. 從緩存中獲取MapperMethod對象

  4. 執(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)?,返回類型)?/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的哪個方法

      // 無返回值或者有結(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)換過程如下:

  1. 通過MapperMethod.SqlCommand. type+MapperMethod.MethodSignature.returnType來確定需要調(diào)用SqlSession中的那個方法

  2. 通過MapperMethod.SqlCommand. name來找到需要執(zhí)行方法的全類名

  3. 通過MapperMethod.MethodSignature.paramNameResolver來轉(zhuǎn)換需要傳遞的參數(shù)

SqlSession

在Mybatis中SqlSession相當(dāng)于一個門面,所有對數(shù)據(jù)庫的操作都需要通過SqlSession接口,SqlSession中定義了所有對數(shù)據(jù)庫的操作方法,如數(shù)據(jù)庫讀寫命令、獲取映射器、管理事務(wù)等,也是Mybatis中為數(shù)不多的有注釋的類。

Mybatis代理模塊有哪些以及如何執(zhí)行

流程圖

Mybatis代理模塊有哪些以及如何執(zhí)行

通過上面的源碼解析,可以發(fā)現(xiàn)Mybatis面向接口編程是通過JDK動態(tài)代理模式來實(shí)現(xiàn)的。主要執(zhí)行流程是:

  1. 在映射文件初始化完成后,將對應(yīng)的Mapper接口的代理工廠類MapperProxyFactory注冊到MapperRegistry

  2. 每次操作數(shù)據(jù)庫時,sqlSession通過MapperProxyFactory獲取Mapper接口的代理類

  3. 代理類通過增強(qiáng)器MapperProxy調(diào)用XML映射文件中SQL節(jié)點(diǎn)的封裝類MapperMethod

  4. 通過MapperMethod將Mybatis 面向接口的編程模型轉(zhuǎn)換成iBatis編程模型(SqlSession模型)

  5. 通過SqlSession完成對數(shù)據(jù)庫的操作

上述就是小編為大家分享的Mybatis代理模塊有哪些以及如何執(zhí)行了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI