Mybatis源碼解讀

来源:https://www.cnblogs.com/konghuanxi/archive/2022/05/13/16267467.html
-Advertisement-
Play Games

問題 Mybatis四大對象的創建順序? Mybatis插件的執行順序? 工程創建 環境:Mybatis(3.5.9) mybatis-demo,參考官方文檔 簡單示例 這裡只放出main方法的示例,其餘類請看demo工程。 public static void main(String[] args ...


問題

  1. Mybatis四大對象的創建順序?
  2. Mybatis插件的執行順序?

工程創建

環境:Mybatis(3.5.9)

mybatis-demo,參考官方文檔

簡單示例

這裡只放出main方法的示例,其餘類請看demo工程。

public static void main(String[] args) throws Exception {
    // 配置文件路徑
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    // 1.讀取配置,創建SqlSessionFactory
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    // 2.通過工廠獲取SqlSession
    SqlSession session = sqlSessionFactory.openSession();
    try {
        // 3.獲取mapper代理對象
        StudentMapper mapper = session.getMapper(StudentMapper.class);
        // 4.執行查詢,此處才真正連接資料庫
        System.out.println(mapper.selectByName("張三"));
    } finally {
        // 5.關閉連接
        session.close();
    }
}

Mapper的創建

我們使用Mybatis操作資料庫,主要是通過mapper對象(在hibernate中叫dao對象)。

那麼,我們不按順序從讀取配置初始化開始講,直接看看mapper對象是如何獲取與執行的。

  1. 獲取mapper

    // StudentMapper mapper = session.getMapper(StudentMapper.class);
    DefaultSqlSession.getMapper(Class<T> type)  -->
    Configuration.getMapper(Class<T> type, SqlSession sqlSession) -->
    MapperRegistry.getMapper(Class<T> type, SqlSession sqlSession) -->
    MapperProxyFactory.newInstance(SqlSession sqlSession) -->
    MapperProxyFactory.newInstance(MapperProxy<T> mapperProxy)
    

    咱們來看看MapperProxyFactory.newInstance(MapperProxy mapperProxy)的實現

    protected T newInstance(MapperProxy<T> mapperProxy) {
      // 可以轉換成這樣,返回的是StudentMapper的代理對象
      // final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, StudentMapper.class, methodCache);
      // Proxy.newProxyInstance(StudentMapper.class.getClassLoader(), new Class[] { StudentMapper.class }, mapperProxy);
      return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
    }
    

    也就是說,實際返回的是MapperProxy對象,StudentMapper被代理了。

  2. 執行mapper的方法

    已知mapper對象被代理了,那麼執行mapper的所有方法,都會先經過MapperProxy的invoke方法

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      try {
        // 如果執行的是Object的方法,則直接執行,不繼續處理mybatis的邏輯
        if (Object.class.equals(method.getDeclaringClass())) {
          // 舉例,如果執行的是mapper.toString(),則進入此判斷
          return method.invoke(this, args);
        } else {
          // cachedInvoker(method):創建MapperMethodInvoker並緩存起來
          return cachedInvoker(method).invoke(proxy, method, args, sqlSession);
        }
      } catch (Throwable t) {
        throw ExceptionUtil.unwrapThrowable(t);
      }
    }
    

    cachedInvoker(method)返回的是PlainMethodInvoker,繼續進去看看

    // PlainMethodInvoker的方法
    public Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable {
      return mapperMethod.execute(sqlSession, args);
    }
    
    // MapperMethod#execute(SqlSession sqlSession, Object[] args)
    public Object execute(SqlSession sqlSession, Object[] args) {
      Object result;
      switch (command.getType()) {
        case INSERT: {
          ......
          break;
        }
        case UPDATE: {
          ......
          break;
        }
        case DELETE: {
          ......
          break;
        }
        case SELECT:
          ......
          break;
        case FLUSH:
          result = sqlSession.flushStatements();
          break;
        default:
          throw new BindingException("Unknown execution method for: " + command.getName());
      }
      ......
      return result;
    }
    

    終於,看到了熟悉insert、update關鍵字,這裡就是具體解析執行sql,並返回結果的邏輯。咱們先略過。回去看看是如何載入配置以及生成SqlSession的。

SqlSessionFactory

SqlSessionFactory的生成過程如下

public SqlSessionFactory build(InputStream inputStream) {
  return build(inputStream, null, null);
}

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
  try {
    // xml配置解析類
    XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
    // build方法返回DefaultSqlSessionFactory
    // 主要看parser.parse()
    return build(parser.parse());
  } catch (Exception e) {
    throw ExceptionFactory.wrapException("Error building SqlSession.", e);
  } finally {
    // 異常上下文對象,線程內共用
    ErrorContext.instance().reset();
    try {
      inputStream.close();
    } catch (IOException e) {
      // Intentionally ignore. Prefer previous error.
    }
  }
}

public SqlSessionFactory build(Configuration config) {
  return new DefaultSqlSessionFactory(config);
}

下麵來看看parser.parse()方法

// XMLConfigBuilder#parse()
public Configuration parse() {
  if (parsed) {
    throw new BuilderException("Each XMLConfigBuilder can only be used once.");
  }
  parsed = true;
  // parser.evalNode("/configuration"):獲取configuration節點
  // 例如:<configuration> xxx </configuration>
  // parseConfiguration才是重點
  parseConfiguration(parser.evalNode("/configuration"));
  return configuration;
}

// 這是重點
private void parseConfiguration(XNode root) {
  try {
    propertiesElement(root.evalNode("properties"));
    Properties settings = settingsAsProperties(root.evalNode("settings"));
    loadCustomVfs(settings);
    loadCustomLogImpl(settings);
    typeAliasesElement(root.evalNode("typeAliases"));
    pluginElement(root.evalNode("plugins"));
    objectFactoryElement(root.evalNode("objectFactory"));
    objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
    reflectorFactoryElement(root.evalNode("reflectorFactory"));
    settingsElement(settings);
    // 環境配置
    environmentsElement(root.evalNode("environments"));
    databaseIdProviderElement(root.evalNode("databaseIdProvider"));
    typeHandlerElement(root.evalNode("typeHandlers"));
    // 映射器配置
    mapperElement(root.evalNode("mappers"));
  } catch (Exception e) {
    throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
  }
}

詳細XML的配置請參考官網:mybatis – MyBatis 3 | 配置

這裡,咱們只講環境配置,其他的篇幅有限,請自行查看源碼。

Untitled

SqlSession

接下來看看SqlSession的創建

// DefaultSqlSessionFactory#openSession() -->
// DefaultSqlSessionFactory#openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false)
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
  Transaction tx = null;
  try {
    // 預設環境
    final Environment environment = configuration.getEnvironment();
    // 事務工廠
    final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
    // 上面那兩個對象,在創建SqlSessionFactory時,就已經創建好了
    // 通過事務工廠創建事務
    tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
    // 創建mybatis四大對象之一的Executor
    final Executor executor = configuration.newExecutor(tx, execType);
    return new DefaultSqlSession(configuration, executor, autoCommit);
  } catch (Exception e) {
    closeTransaction(tx); // may have fetched a connection so lets call close()
    throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
  } finally {
    ErrorContext.instance().reset();
  }
}

看看四大對象之一Executor的創建

// Configuration#newExecutor(Transaction transaction, ExecutorType executorType)
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
  // 判斷需要創建的執行器的類型
  executorType = executorType == null ? defaultExecutorType : executorType;
  executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
  Executor executor;
  if (ExecutorType.BATCH == executorType) {
    // 批處理執行器
    executor = new BatchExecutor(this, transaction);
  } else if (ExecutorType.REUSE == executorType) {
    // 重用執行器
    executor = new ReuseExecutor(this, transaction);
  } else {
    // 簡單處理器(預設)
    executor = new SimpleExecutor(this, transaction);
  }
  // 是否啟用二級緩存(二級緩存預設啟用)
  if (cacheEnabled) {
    // 此處使用的是裝飾器模式,對executor進行二次包裝
    executor = new CachingExecutor(executor);
  }
  // 這塊是mybatis的插件處理,用代理的方式,以後再開文章講
  executor = (Executor) interceptorChain.pluginAll(executor);
  return executor;
}

Mapper的執行

Mapper的創建一節,講到mapper執行會被代理。

下麵就以StudentMapper為例,講講mapper的執行。

public interface StudentMapper {
    List<Student> selectByName(@Param("name") String name);
}

當執行selectByName時候,進入到MapperMethod#execute(SqlSession sqlSession, Object[] args)方法。

public Object execute(SqlSession sqlSession, Object[] args) {
  Object result;
  switch (command.getType()) {
    ......
    // 忽略insert、update、delete的邏輯,直接看select
    case SELECT:
      // 如果返回null或者設置了自定義的結果處理器
      if (method.returnsVoid() && method.hasResultHandler()) {
        executeWithResultHandler(sqlSession, args);
        result = null;
      // 如果返回集合或者數組,我們的查詢會進到這裡,因為selectByName返回值是List
      // 這是入口
      } else if (method.returnsMany()) {
        result = executeForMany(sqlSession, args);
      // 如果返回map
      } 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;
}

繼續看executeForMany方法

private <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
  List<E> result;
  // 參數轉換,如果參數有註解,則會轉成map,且可使用param1, param2
  // 例如:@Param("name")會轉成  {"name":xxx, "param1": xxx}
  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);
  }
  // 如果result不能強轉成方法的返回值(在此例子中getReturnType就是List<Studet>)
  if (!method.getReturnType().isAssignableFrom(result.getClass())) {
    if (method.getReturnType().isArray()) {
      return convertToArray(result);
    } else {
      return convertToDeclaredCollection(sqlSession.getConfiguration(), result);
    }
  }
  return result;
}

繼續看,因為案例中沒用到分頁,所以執行的是sqlSession.selectList(command.getName(), param);

// DefaultSqlSession#selectList(String statement, Object parameter) -->
// DefaultSqlSession#selectList(String statement, Object parameter, RowBounds rowBounds) -->
// DefaultSqlSession#selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) -->
private <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
  try {
    // MapperStatement在前面解析xml時,就已經創建了
    // 忘了就看看創建SqlSessionFactory時是如何解析xml文件的mappers節點的
    MappedStatement ms = configuration.getMappedStatement(statement);
    // 執行器執行查詢方法
    return executor.query(ms, wrapCollection(parameter), rowBounds, handler);
  } catch (Exception e) {
    throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
  } finally {
    ErrorContext.instance().reset();
  }
}

繼續看,executor.query方法,Mybatis-PageHelper插件就是通過攔截query方法,插入分頁參數的。

// CachingExecutor
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
  // 對sql進行預處理
	BoundSql boundSql = ms.getBoundSql(parameterObject);
  // 創建一級緩存的key
  CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
  // 這是入口
  return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}

public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
  Cache cache = ms.getCache();
  // 有緩存的邏輯
  if (cache != null) {
    flushCacheIfRequired(ms);
    if (ms.isUseCache() && resultHandler == null) {
      ensureNoOutParams(ms, boundSql);
      @SuppressWarnings("unchecked")
      List<E> list = (List<E>) tcm.getObject(cache, key);
      if (list == null) {
        list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
        tcm.putObject(cache, key, list); // issue #578 and #116
      }
      return list;
    }
  }
  // delegate是SimpleExecutor
  // 這是入口
  return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}

// BaseExecutor
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
  ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
  if (closed) {
    throw new ExecutorException("Executor was closed.");
  }
  // 是否要清除緩存,預設設置是如果非select方法,都會清除緩存。
  if (queryStack == 0 && ms.isFlushCacheRequired()) {
    clearLocalCache();
  }
  List<E> list;
  try {
    queryStack++;
    // 從一級緩存提取數據
    list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
    if (list != null) {
      handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
    } else {
      // 從資料庫查詢數據
      // 這是入口
      list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
    }
  } finally {
    queryStack--;
  }
  if (queryStack == 0) {
    // 懶載入相關
    for (DeferredLoad deferredLoad : deferredLoads) {
      deferredLoad.load();
    }
    // issue #601
    deferredLoads.clear();
    if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
      // issue #482
      clearLocalCache();
    }
  }
  return list;
}

private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
  List<E> list;
  localCache.putObject(key, EXECUTION_PLACEHOLDER);
  try {
    // 這是入口
    list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
  } finally {
    localCache.removeObject(key);
  }
  // 結果放入一級緩存
  localCache.putObject(key, list);
  if (ms.getStatementType() == StatementType.CALLABLE) {
    localOutputParameterCache.putObject(key, parameter);
  }
  return list;
}

下麵,重點來了,準備了這麼久,終於要查詢資料庫了

// SimpleExecutor
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
  Statement stmt = null;
  try {
    Configuration configuration = ms.getConfiguration();
    // 重點又來了,mybatis四大對象的3個,在這裡創建
    // 按順序是:ParameterHandler、ParameterHandler、StatementHandler
    // 又一個裝飾器模式,實際創建的是PreparedStatementHandler(預設),但是使用RoutingStatementHandler又包了一層
    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
    // 創建jdbc的statement對象,直到這裡,才會真正獲取資料庫連接
		stmt = prepareStatement(handler, ms.getStatementLog());
    // 執行查詢,並使用resultHandler處理結果
    return handler.query(stmt, resultHandler);
  } finally {
    closeStatement(stmt);
  }
}

答案

  1. 創建順序為:Executor、ParameterHandler、ParameterHandler、StatementHandler
  2. 插件的執行順序,如果都命中同一個方法,那麼順序為,越晚註冊的插件,越先執行(因為代理)

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 到目前為止,我們知道Spring創建Bean對象有5中方法,分別是: 使用FactoryBean的getObject方法創建 使用BeanPostProcessor的子介面InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiati ...
  • package com.exception.demo01;public class demo01 { public static void main(String[] args) { try{new demo01().a();}//StackOverflowError異常 catch (Throwa ...
  • 介紹:本文用的經典的前後端分離開源項目ruoyi Gitee鏈接地址:https://gitee.com/y_project/RuoYi 一、拉取項目: 利用Git把項目拉取到本地,也可以直接利用idea工具拉取,如圖點擊Get from VCS 填入遠程倉庫地址url,點擊clonde 等待一段時 ...
  • 博客推行版本更新,成果積累制度,已經寫過的博客還會再次更新,不斷地琢磨,高質量高數量都是要追求的,工匠精神是學習必不可少的精神。因此,大家有何建議歡迎在評論區踴躍發言,你們的支持是我最大的動力,你們敢投,我就敢肝 ...
  • 本文緊接上文的AQS源碼,如果對於ReentrantLock沒有基礎可以先閱讀我的上一篇文章學習ReentrantLock的源碼 ReentrantLock鎖重入原理 重入加鎖其實就是將AQS的state進行加一操作 然後釋放鎖資源將AQS的state進行減一操作 當state為0時才會徹底的釋放鎖 ...
  • 目錄 一.簡介 二.效果演示 三.源碼下載 四.猜你喜歡 零基礎 OpenGL (ES) 學習路線推薦 : OpenGL (ES) 學習目錄 >> OpenGL ES 基礎 零基礎 OpenGL (ES) 學習路線推薦 : OpenGL (ES) 學習目錄 >> OpenGL ES 轉場 零基礎 O ...
  • 鑒於本屆諸多同學在一開始接觸到軟體構造課程時出現了對於Github的使用以及對於文件目錄的設置等諸多問題,本人雖然很菜,但是願意寫本篇博客以記錄一些前置內容的操作方法,如有謬誤,敬請指正!謝謝! ...
  • 背景 基於elasticsearch-5.6.0 機器配置:3個雲ecs節點,16G,4核,機械硬碟 優化前,寫入速度平均3000條/s,一遇到壓測,寫入速度驟降,甚至es直接頻率gc、oom等;優化後,寫入速度平均8000條/s,遇到壓測,能在壓測結束後30分鐘內消化完數據,各項指標回歸正常。 生 ...
一周排行
    -Advertisement-
    Play Games
  • Timer是什麼 Timer 是一種用於創建定期粒度行為的機制。 與標準的 .NET System.Threading.Timer 類相似,Orleans 的 Timer 允許在一段時間後執行特定的操作,或者在特定的時間間隔內重覆執行操作。 它在分散式系統中具有重要作用,特別是在處理需要周期性執行的 ...
  • 前言 相信很多做WPF開發的小伙伴都遇到過表格類的需求,雖然現有的Grid控制項也能實現,但是使用起來的體驗感並不好,比如要實現一個Excel中的表格效果,估計你能想到的第一個方法就是套Border控制項,用這種方法你需要控制每個Border的邊框,並且在一堆Bordr中找到Grid.Row,Grid. ...
  • .NET C#程式啟動閃退,目錄導致的問題 這是第2次踩這個坑了,很小的編程細節,容易忽略,所以寫個博客,分享給大家。 1.第一次坑:是windows 系統把程式運行成服務,找不到配置文件,原因是以服務運行它的工作目錄是在C:\Windows\System32 2.本次坑:WPF桌面程式通過註冊表設 ...
  • 在分散式系統中,數據的持久化是至關重要的一環。 Orleans 7 引入了強大的持久化功能,使得在分散式環境下管理數據變得更加輕鬆和可靠。 本文將介紹什麼是 Orleans 7 的持久化,如何設置它以及相應的代碼示例。 什麼是 Orleans 7 的持久化? Orleans 7 的持久化是指將 Or ...
  • 前言 .NET Feature Management 是一個用於管理應用程式功能的庫,它可以幫助開發人員在應用程式中輕鬆地添加、移除和管理功能。使用 Feature Management,開發人員可以根據不同用戶、環境或其他條件來動態地控制應用程式中的功能。這使得開發人員可以更靈活地管理應用程式的功 ...
  • 在 WPF 應用程式中,拖放操作是實現用戶交互的重要組成部分。通過拖放操作,用戶可以輕鬆地將數據從一個位置移動到另一個位置,或者將控制項從一個容器移動到另一個容器。然而,WPF 中預設的拖放操作可能並不是那麼好用。為瞭解決這個問題,我們可以自定義一個 Panel 來實現更簡單的拖拽操作。 自定義 Pa ...
  • 在實際使用中,由於涉及到不同編程語言之間互相調用,導致C++ 中的OpenCV與C#中的OpenCvSharp 圖像數據在不同編程語言之間難以有效傳遞。在本文中我們將結合OpenCvSharp源碼實現原理,探究兩種數據之間的通信方式。 ...
  • 一、前言 這是一篇搭建許可權管理系統的系列文章。 隨著網路的發展,信息安全對應任何企業來說都越發的重要,而本系列文章將和大家一起一步一步搭建一個全新的許可權管理系統。 說明:由於搭建一個全新的項目過於繁瑣,所有作者將挑選核心代碼和核心思路進行分享。 二、技術選擇 三、開始設計 1、自主搭建vue前端和. ...
  • Csharper中的表達式樹 這節課來瞭解一下表示式樹是什麼? 在C#中,表達式樹是一種數據結構,它可以表示一些代碼塊,如Lambda表達式或查詢表達式。表達式樹使你能夠查看和操作數據,就像你可以查看和操作代碼一樣。它們通常用於創建動態查詢和解析表達式。 一、認識表達式樹 為什麼要這樣說?它和委托有 ...
  • 在使用Django等框架來操作MySQL時,實際上底層還是通過Python來操作的,首先需要安裝一個驅動程式,在Python3中,驅動程式有多種選擇,比如有pymysql以及mysqlclient等。使用pip命令安裝mysqlclient失敗應如何解決? 安裝的python版本說明 機器同時安裝了 ...