mybatis - MybatisAutoConfiguration

来源:https://www.cnblogs.com/elvinle/archive/2020/02/11/12297104.html
-Advertisement-
Play Games

一. MybatisProperties 在使用 mybatis 時, 還需要對mapper進行配置: mybatis: mapper-locations: classpath:mapper/**Mapper.xml 這些配置其實是映射到 mybatis-spring-boot-autoconfig ...


一. MybatisProperties 

在使用 mybatis 時, 還需要對mapper進行配置:

mybatis:
    mapper-locations: classpath:mapper/**Mapper.xml

這些配置其實是映射到 mybatis-spring-boot-autoconfigure 包下的  MybatisProperties 文件中的.

@ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX)
public class MybatisProperties {

  public static final String MYBATIS_PREFIX = "mybatis";

  /**
   * Location of MyBatis xml config file.
   */
  private String configLocation;

  /**
   * Locations of MyBatis mapper files.
   */
  private String[] mapperLocations;

  /**
   * Packages to search type aliases. (Package delimiters are ",; \t\n")
   */
  private String typeAliasesPackage;

  /**
   * Packages to search for type handlers. (Package delimiters are ",; \t\n")
   */
  private String typeHandlersPackage;

  /**
   * Indicates whether perform presence check of the MyBatis xml config file.
   */
  private boolean checkConfigLocation = false;

  /**
   * Execution mode for {@link org.mybatis.spring.SqlSessionTemplate}.
   */
  private ExecutorType executorType;

  /**
   * Externalized properties for MyBatis configuration.
   */
  private Properties configurationProperties;

  /**
   * A Configuration object for customize default settings. If {@link #configLocation}
   * is specified, this property is not used.
   */
  @NestedConfigurationProperty
  private Configuration configuration;
......
}

 

二. MybatisAutoConfiguration 

MybatisAutoConfiguration 是 mybatis-spring-boot-autoconfigure 中的一個配置類.

在這個配置類中, 主要加入了兩個組件: SqlSessionFactory 和 SqlSessionTemplate

1. SqlSessionFactory

  @Bean
  @ConditionalOnMissingBean
  public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
    factory.setDataSource(dataSource);
    factory.setVfs(SpringBootVFS.class);
    if (StringUtils.hasText(this.properties.getConfigLocation())) {
      factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
    }
    Configuration configuration = this.properties.getConfiguration();
    if (configuration == null && !StringUtils.hasText(this.properties.getConfigLocation())) {
      configuration = new Configuration();
    }
    if (configuration != null && !CollectionUtils.isEmpty(this.configurationCustomizers)) {
      for (ConfigurationCustomizer customizer : this.configurationCustomizers) {
        customizer.customize(configuration);
      }
    }
    factory.setConfiguration(configuration);
    if (this.properties.getConfigurationProperties() != null) {
      factory.setConfigurationProperties(this.properties.getConfigurationProperties());
    }
    if (!ObjectUtils.isEmpty(this.interceptors)) {
      factory.setPlugins(this.interceptors);
    }
    if (this.databaseIdProvider != null) {
      factory.setDatabaseIdProvider(this.databaseIdProvider);
    }
    if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
      factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
    }
    if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
      factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
    }
    if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
      factory.setMapperLocations(this.properties.resolveMapperLocations());
    }

    return factory.getObject();
  }

(從名字可以看出來, SqlSessionFactory 是 SqlSession的一個工廠類. SqlSession 這個類很重要, 裡面定義了 資料庫的一套增刪改查操作的規範.)

MybatisProperties 中的配置會在這個方法中進行解析.

1. 創建了 Configuration 配置類(後面會用到, 這個類也很重要)的實例

2. 通過 factory.getObject() 方法創建了 SqlSessionFactory 類的實例

創建的過程中, 又調用了 protected SqlSessionFactory buildSqlSessionFactory() 方法進行創建, 創建過程比較多, 留給後面在解析.

 

2. SqlSessionTemplate 

  @Bean
  @ConditionalOnMissingBean
  public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    ExecutorType executorType = this.properties.getExecutorType();
    if (executorType != null) {
      return new SqlSessionTemplate(sqlSessionFactory, executorType);
    } else {
      return new SqlSessionTemplate(sqlSessionFactory);
    }
  }

SqlSessionTemplate 這個類 實現了 SqlSession 介面,  也就是說, 他也有一套 資料庫的 增刪改查的方法. 先看一下構造過程:

  public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType());
  }

 |
 |
\|/

  public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) {
    this(sqlSessionFactory, executorType,
        new MyBatisExceptionTranslator(
            sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), true));
  }

 |
 |
\|/

  public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,
      PersistenceExceptionTranslator exceptionTranslator) {

    notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
    notNull(executorType, "Property 'executorType' is required");

    this.sqlSessionFactory = sqlSessionFactory;
    this.executorType = executorType;
    this.exceptionTranslator = exceptionTranslator;
    this.sqlSessionProxy = (SqlSession) newProxyInstance(
        SqlSessionFactory.class.getClassLoader(),
        new Class[] { SqlSession.class },
        new SqlSessionInterceptor());
  }

這裡初始化了一個很重要的屬性:  sqlSessionProxy. 

sqlSessionProxy 是為 SqlSession 創建了一個代理類, 且代理方法為:  SqlSessionInterceptor

 

看一個 實現了 SqlSession 介面中的  selectOne 方法:

  @Override
  public <T> T selectOne(String statement, Object parameter) {
    return this.sqlSessionProxy.<T> selectOne(statement, parameter);
  }

可以看到, 在調用 selectOne 方法的時候, 其實就是調用了 SqlSessionInterceptor 的 invoke 方法.

 


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

-Advertisement-
Play Games
更多相關文章
  • 前言 準確的說eval處理過的代碼應該叫做壓縮代碼,不過效果上算是加密過了一樣!很多小伙伴不想直接讓別人看到自己的js代碼往往就會採取這樣的處理措施。不過,其實這樣的方法只能防禦那些小白。對於真正的大佬來說,破解就是秒秒鐘的事!真的就是秒秒鐘!話不多說,我們直接進入正題! 演示代碼: 操作步驟 1. ...
  • 前言 微信紅包業務,發紅包之後如果24小時之內沒有被領取完就自動過期失效。 架構設計 業務流程 老闆發紅包,此時緩存初始化紅包個數,紅包金額(單位分),並非同步入庫。 紅包數據入延遲隊列,唯一標識+失效時間 紅包數據出延遲隊列,根據唯一標識清空紅包緩存數據、非同步更新資料庫、非同步退回紅包金額 代碼案例 ...
  • 前言 截至2020年,Java仍然是構建Web應用程式的最流行的編程語言之一,儘管它必須面對來自Go,Python和TypeScript等新型語言的激烈競爭。 在Java世界內部,Spring框架已成為微服務開發的事實上的標準,通過諸如Spring Boot和Spring Data之類的庫,該框架易 ...
  • 本文將介紹一個重要的 "數據結構" —棧,和之前講到的 "鏈表" 、 "數組" 一樣也是一種數據呈 線性排列 的數據結構,不過在這種結構中,我們只能訪問最新添加的數據。棧就像是一摞書,拿到新書時我們會把它放在書堆的最上面,取書時也只能從最上面的新書開始取。 棧 如上就是棧的概念圖,現在存儲在棧中的只 ...
  • 作為一個Java從業者,面試的時候肯定會被問到過HashMap ...
  • 經過這次在公司實習中獲取到的經歷,我發現確實有時候書本上的知識發揮的作用微乎其微,好像是被問題打了太極拳一樣,你明明想去攻剋這個地方,他卻給你報了其他地方的錯誤。 平常的一些小項目根本就不能匹配到企業級別的開發經驗尤其我也不是ACM得獎的大佬,更是覺得尤為不適應,還好經過4個月左右的實習時間,我漸漸 ...
  • 結構體模板 1 struct STU 2 { 3 string name; //用string可以代替char 4 string num; 5 int s; 6 }; sort是用快速排序實現的,屬於不穩定排序,stable_sort是用歸併排序實現的,因此是穩定的。從此以後,為了保險起見我打算使用 ...
  • handler參數映射: 接下來就是Spring的各個處理細節了,無論框架如何瘋轉其實我們處理請求的流程是不變的,設計到的操作也是固定的,舉個例子,當我們要實現一個登陸功能時: 創建一個用於處理登錄請求的Servlet 實現doget等其他http方法(一些情況可能根據業務需要限制請求方法) 從re ...
一周排行
    -Advertisement-
    Play Games
  • 基於.NET Framework 4.8 開發的深度學習模型部署測試平臺,提供了YOLO框架的主流系列模型,包括YOLOv8~v9,以及其系列下的Det、Seg、Pose、Obb、Cls等應用場景,同時支持圖像與視頻檢測。模型部署引擎使用的是OpenVINO™、TensorRT、ONNX runti... ...
  • 十年沉澱,重啟開發之路 十年前,我沉浸在開發的海洋中,每日與代碼為伍,與演算法共舞。那時的我,滿懷激情,對技術的追求近乎狂熱。然而,隨著歲月的流逝,生活的忙碌逐漸占據了我的大部分時間,讓我無暇顧及技術的沉澱與積累。 十年間,我經歷了職業生涯的起伏和變遷。從初出茅廬的菜鳥到逐漸嶄露頭角的開發者,我見證了 ...
  • C# 是一種簡單、現代、面向對象和類型安全的編程語言。.NET 是由 Microsoft 創建的開發平臺,平臺包含了語言規範、工具、運行,支持開發各種應用,如Web、移動、桌面等。.NET框架有多個實現,如.NET Framework、.NET Core(及後續的.NET 5+版本),以及社區版本M... ...
  • 前言 本文介紹瞭如何使用三菱提供的MX Component插件實現對三菱PLC軟元件數據的讀寫,記錄了使用電腦模擬,模擬PLC,直至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1. PLC開發編程環境GX Works2,GX Works2下載鏈接 https:// ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • 1、jQuery介紹 jQuery是什麼 jQuery是一個快速、簡潔的JavaScript框架,是繼Prototype之後又一個優秀的JavaScript代碼庫(或JavaScript框架)。jQuery設計的宗旨是“write Less,Do More”,即倡導寫更少的代碼,做更多的事情。它封裝 ...
  • 前言 之前的文章把js引擎(aardio封裝庫) 微軟開源的js引擎(ChakraCore))寫好了,這篇文章整點js代碼來測一下bug。測試網站:https://fanyi.youdao.com/index.html#/ 逆向思路 逆向思路可以看有道翻譯js逆向(MD5加密,AES加密)附完整源碼 ...
  • 引言 現代的操作系統(Windows,Linux,Mac OS)等都可以同時打開多個軟體(任務),這些軟體在我們的感知上是同時運行的,例如我們可以一邊瀏覽網頁,一邊聽音樂。而CPU執行代碼同一時間只能執行一條,但即使我們的電腦是單核CPU也可以同時運行多個任務,如下圖所示,這是因為我們的 CPU 的 ...
  • 掌握使用Python進行文本英文統計的基本方法,並瞭解如何進一步優化和擴展這些方法,以應對更複雜的文本分析任務。 ...
  • 背景 Redis多數據源常見的場景: 分區數據處理:當數據量增長時,單個Redis實例可能無法處理所有的數據。通過使用多個Redis數據源,可以將數據分區存儲在不同的實例中,使得數據處理更加高效。 多租戶應用程式:對於多租戶應用程式,每個租戶可以擁有自己的Redis數據源,以確保數據隔離和安全性。 ...