持久層Mybatis3底層源碼分析,原理解析

来源:https://www.cnblogs.com/dream-sun/archive/2019/03/26/10603931.html
-Advertisement-
Play Games

Mybatis-持久層的框架,功能是非常強大的,對於移動互聯網的高併發 和 高性能是非常有利的,相對於Hibernate全自動的ORM框架,Mybatis簡單,易於學習,sql編寫在xml文件中,和代碼分離,易於維護,屬於半ORM框架,對於面向用戶層面的互聯網業務性能和併發,可以通過sql優化解決一 ...


Mybatis-持久層的框架,功能是非常強大的,對於移動互聯網的高併發 和 高性能是非常有利的,相對於Hibernate全自動的ORM框架,Mybatis簡單,易於學習,sql編寫在xml文件中,和代碼分離,易於維護,屬於半ORM框架,對於面向用戶層面的互聯網業務性能和併發,可以通過sql優化解決一些問題。

現如今大部分公司都在使用Mybatis,所以我們要理解框架底層的原理。閑話不多說。

Mybatis框架的核心入口 是SqlSessionFactory介面,我們先看一下它的代碼

public interface SqlSessionFactory {

  SqlSession openSession();

  SqlSession openSession(boolean autoCommit);
  SqlSession openSession(Connection connection);
  SqlSession openSession(TransactionIsolationLevel level);

  SqlSession openSession(ExecutorType execType);
  SqlSession openSession(ExecutorType execType, boolean autoCommit);
  SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
  SqlSession openSession(ExecutorType execType, Connection connection);

  Configuration getConfiguration();

}
SqlSessionFactory

SqlSessionFactory介面很多重載的openSession方法,返回sqlSession類型 對象, 還有Configuration類(這個類非常強大,下麵會梳理),我們先看一下SqlSession的代碼

public interface SqlSession extends Closeable {

 
  <T> T selectOne(String statement);


  <T> T selectOne(String statement, Object parameter);

  <E> List<E> selectList(String statement);

  <E> List<E> selectList(String statement, Object parameter);

  <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds);

  <K, V> Map<K, V> selectMap(String statement, String mapKey);
  <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey);

  <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds);

  <T> Cursor<T> selectCursor(String statement);
  <T> Cursor<T> selectCursor(String statement, Object parameter);

  <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds);


  void select(String statement, Object parameter, ResultHandler handler);


  void select(String statement, ResultHandler handler);


  List<BatchResult> flushStatements();

  /**
   * Closes the session
   */
  @Override
  void close();

  void clearCache();


  Configuration getConfiguration();


  <T> T getMapper(Class<T> type);

  Connection getConnection();
}
sqlSeesion

只是展示了部分代碼,但我們可以看到,sqlSeesion裡面 大多數方法是 增刪改查的執行方法,包括查詢返回不同的數據結構,比較註意的是clearCache()和getConnection()方法,一個是清楚緩存,一個是獲取連接,獲取資料庫連接在這不在描述, 為什麼要註意清楚緩存那,因為mybatis框架是實現了 緩存的,分為一級緩存,二級緩存,當增刪改的時候就會調用此方法,刪除緩存(後續會專門寫一篇文章來分析Mybatis緩存),先在這給大家熟悉一下。

上面的SqlSessionFactory和SqlSeesion都是介面,我們在看一下實現類DefaultSqlSessionFactory和DefaultSqlSession,下麵展示DefaultSqlSessionFactory的比較核心的代碼

 1   private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
 2     Transaction tx = null;
 3     try {
 4       final Environment environment = configuration.getEnvironment();
 5       final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
 6       tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
 7       final Executor executor = configuration.newExecutor(tx, execType);
 8       return new DefaultSqlSession(configuration, executor, autoCommit);
 9     } catch (Exception e) {
10       closeTransaction(tx); // may have fetched a connection so lets call close()
11       throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
12     } finally {
13       ErrorContext.instance().reset();
14     }
15   }
DefaultSqlSessionFactory

其實SqlSessionFactory中的多個重載openSeesion方法最終都是執行的這個方法,我們可以看到這個方法中 通過 configuration屬性 獲取到Executor 執行器對象,DefaultSqlSession構造器把這configuration和executor當成構造參數,初始化創建一個 DefaultSqlSession對象,然後我們在展示一下DefaultSqlSession代碼中的大家一看就理解的代碼

 1   public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
 2     try {
 3       MappedStatement ms = configuration.getMappedStatement(statement);
 4       return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
 5     } catch (Exception e) {
 6       throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
 7     } finally {
 8       ErrorContext.instance().reset();
 9     }
10   }
DefaultSession

看到這個方法大家估計就會看明白了,底層執行的就是 通過Executor 對象執行的 查詢, 通過configuration獲取到 要執行的sql,獲取到我們需要的結果。

從上面代碼可以看出 Configuration 類無處不在,那我們就去看一下源碼

 1 public class Configuration {
 2 
 3   protected Environment environment;
 4 
 5   protected boolean safeRowBoundsEnabled;
 6   protected boolean safeResultHandlerEnabled = true;
 7   protected boolean mapUnderscoreToCamelCase;
 8   protected boolean aggressiveLazyLoading;
 9   protected boolean multipleResultSetsEnabled = true;
10   protected boolean useGeneratedKeys;
11   protected boolean useColumnLabel = true;
12   protected boolean cacheEnabled = true;
13   protected boolean callSettersOnNulls;
14   protected boolean useActualParamName = true;
15   protected boolean returnInstanceForEmptyRow;
16 
17   protected String logPrefix;
18   protected Class <? extends Log> logImpl;
19   protected Class <? extends VFS> vfsImpl;
20   protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION;
21   protected JdbcType jdbcTypeForNull = JdbcType.OTHER;
22   protected Set<String> lazyLoadTriggerMethods = new HashSet<String>(Arrays.asList(new String[] { "equals", "clone", "hashCode", "toString" }));
23   protected Integer defaultStatementTimeout;
24   protected Integer defaultFetchSize;
25   protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
26   protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL;
27   protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior = AutoMappingUnknownColumnBehavior.NONE;
28 
29   protected Properties variables = new Properties();
30   protected ReflectorFactory reflectorFactory = new DefaultReflectorFactory();
31   protected ObjectFactory objectFactory = new DefaultObjectFactory();
32   protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory();
33 
34   protected boolean lazyLoadingEnabled = false;
35   protected ProxyFactory proxyFactory = new JavassistProxyFactory(); // #224 Using internal Javassist instead of OGNL
36 
37   protected String databaseId;
38   /**
39    * Configuration factory class.
40    * Used to create Configuration for loading deserialized unread properties.
41    *
42    * @see <a href='https://code.google.com/p/mybatis/issues/detail?id=300'>Issue 300 (google code)</a>
43    */
44   protected Class<?> configurationFactory;
45 
46   protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
47   protected final InterceptorChain interceptorChain = new InterceptorChain();
48   protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry();
49   protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry();
50   protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry();
51 
52   protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection");
53   protected final Map<String, Cache> caches = new StrictMap<Cache>("Caches collection");
54   protected final Map<String, ResultMap> resultMaps = new StrictMap<ResultMap>("Result Maps collection");
55   protected final Map<String, ParameterMap> parameterMaps = new StrictMap<ParameterMap>("Parameter Maps collection");
56   protected final Map<String, KeyGenerator> keyGenerators = new StrictMap<KeyGenerator>("Key Generators collection");
57 
58   protected final Set<String> loadedResources = new HashSet<String>();
59   protected final Map<String, XNode> sqlFragments = new StrictMap<XNode>("XML fragments parsed from previous mappers");
60 
61   protected final Collection<XMLStatementBuilder> incompleteStatements = new LinkedList<XMLStatementBuilder>();
62   protected final Collection<CacheRefResolver> incompleteCacheRefs = new LinkedList<CacheRefResolver>();
63   protected final Collection<ResultMapResolver> incompleteResultMaps = new LinkedList<ResultMapResolver>();
64   protected final Collection<MethodResolver> incompleteMethods = new LinkedList<MethodResolver>();
65 
66   /*
67    * A map holds cache-ref relationship. The key is the namespace that
68    * references a cache bound to another namespace and the value is the
69    * namespace which the actual cache is bound to.
70    */
71   protected final Map<String, String> cacheRefMap = new HashMap<String, String>();}
Configuration

上面的代碼都是 Configuration類中的屬性值,上面的boolean 類型的屬性 都是一些配置的屬性,比如useGeneratedKeys是否開啟使用返回主鍵,cacheEnabled是否開啟緩存等等,下麵的Map類型的 就是存儲一些我們項目中需要編寫的sql.xml文件,我們可以通過變數名大致推測出來存儲的結果,比如typeAliasRegistry 存儲的別名,mappedStatements 存儲的sql,resultMaps存儲的結果等,當然這些map的key對應的就是 sql.xml中的唯一的id,分析到現在,我們大致知道Mybatis框架底層的執行原理了。

但是,這時候就有個疑問了,入口類是SqlSessionFactory,那是怎麼載入資源的那,我們通過名稱尋找源碼,可以找到一個SqlSessionFactoryBuilder(這些開發開源框架的牛人們不管技術NB,對類的命名也是很值的大家效仿的),builder--載入, 說明這個類就是載入 SqlSessionFactory,我們看一下代碼

 1 public class SqlSessionFactoryBuilder {
 2 
 3   public SqlSessionFactory build(Reader reader) {
 4     return build(reader, null, null);
 5   }
 6 
 7   public SqlSessionFactory build(Reader reader, String environment) {
 8     return build(reader, environment, null);
 9   }
10 
11   public SqlSessionFactory build(Reader reader, Properties properties) {
12     return build(reader, null, properties);
13   }
14 
15   public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
16     try {
17       XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
18       return build(parser.parse());
19     } catch (Exception e) {
20       throw ExceptionFactory.wrapException("Error building SqlSession.", e);
21     } finally {
22       ErrorContext.instance().reset();
23       try {
24         reader.close();
25       } catch (IOException e) {
26         // Intentionally ignore. Prefer previous error.
27       }
28     }
29   }
30 
31   public SqlSessionFactory build(InputStream inputStream) {
32     return build(inputStream, null, null);
33   }
34 
35   public SqlSessionFactory build(InputStream inputStream, String environment) {
36     return build(inputStream, environment, null);
37   }
38 
39   public SqlSessionFactory build(InputStream inputStream, Properties properties) {
40     return build(inputStream, null, properties);
41   }
42 
43   public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
44     try {
45       XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
46       return build(parser.parse());
47     } catch (Exception e) {
48       throw ExceptionFactory.wrapException("Error building SqlSession.", e);
49     } finally {
50       ErrorContext.instance().reset();
51       try {
52         inputStream.close();
53       } catch (IOException e) {
54         // Intentionally ignore. Prefer previous error.
55       }
56     }
57   }
58     
59   public SqlSessionFactory build(Configuration config) {
60     return new DefaultSqlSessionFactory(config);
61   }
62 
63 }
SqlSessionFactoryBuilder

查看代碼中的build方法,可以看出是 通過流來載入xml文件 ,包括mybatis的配置文件和 sql.xml文件,返回一個DefaultSqlSessionFactory 對象。

本篇文件只是介紹了mybatis的底層執行原理,喜歡深入瞭解的可以自己去深入瞭解一下。

以上是個人理解,歡迎大家來討論,不喜勿噴!謝謝!!

如轉載,請註明轉載地址,謝謝

 


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

-Advertisement-
Play Games
更多相關文章
  • 一、springboot是什麼? 微服務,應該是近年來最火的概念,越來越多的公司開始使用微服務架構,面試中被問到的微服務的概率很高,不管對技術的追求,還是為了進更好的公司,微服務都是我們開發人員的必須要學習的知識。 那麼微服務究竟是什麼呢? 我們通俗的理解方式就是:微服務化的核心就是將傳統的一站式應 ...
  • package main import ( "database/sql" "fmt" "strings" ) import ( _ "github.com/mattn/go-adodb" ) type Mssql struct { *sql.DB dataSource string database ...
  • 列表方法append()和extend()之間的差異: append:在最後追加對象 結果 [1, 2, 3, [4, 5]] extend:通過追加加迭代中的元素來擴展列表。 結果 [1, 2, 3, 4, 5] 作者:阿裡媽媽 鏈接:www.pythonheidong.com/blog/arti ...
  • 1.本地倉庫和apache-mavenbin.zip的下載與解壓 <1.apache-mavenbin.zip下載網址 2.Maven環境變數配置 <1.MAVEN_HOME <2.PATH 3.環境搭建驗證 4自定義數據倉庫的位置(apache-maven.setting.xml)的配置 ...
  • Spring ioc 叫控制反轉,也就是把創建Bean的動作交給Spring去完成。 spring ioc 流程大致為 定位-> 載入->註冊 先說幾個比較有意思的點 1.Spring中的通過IOC生成的Bean是存放在ConcurrentHashMap中的 2.通過xml配置SpringBean時 ...
  • 一、python中如何創建類? 1. 直接定義類 2. 通過type對象創建 在python中一切都是對象 在上面這張圖中,A是我們平常在python中寫的類,它可以創建一個對象a。其實A這個類也是一個對象,它是type類的對象,可以說type類是用來創建類對象的類,我們平常寫的類都是type類創建 ...
  • 題意 "題目鏈接" 題目鏈接 一種做法是直接用歐拉降冪算出$2^p \pmod{p 1}$然後矩陣快速冪。 但是今天學習了一下二次剩餘,也可以用通項公式+二次剩餘做。 就是我們猜想$5$在這個模數下有二次剩餘,拉個板子發現真的有。 然求出來直接做就行了 cpp include define Pair ...
  • 前幾天工作忙得焦頭爛額時,同事問了一下關於Map的特性,剎那間懵了一下,緊接著就想起來了一些關於Map的一些知識,因為只要涉及到Collection集合類時,就會談及Map類,因此理解好Map相關的知識是灰常重要的。 Collection集合類 與 Map類的層次結構,如下圖: Map是用來存儲 K ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...