一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|JavaScript|易語言|

服務器之家 - 編程語言 - Java教程 - Mybatis原理及源碼分析

Mybatis原理及源碼分析

2021-08-09 23:47三不猴子sanbuhouzi Java教程

作為Java程序員Mybatis應該是一個必會框架了,其源碼體量只有Spring 的1/5,也是Hibernate的1/5 ,相比于其他流行框架Mybatis源碼無疑是學習成本最低的,當做年輕人看的第一個框架源碼,無疑是非常好的。

Mybatis原理及源碼分析

作為Java程序員Mybatis應該是一個必會框架了,其源碼體量只有Spring 的1/5,也是Hibernate的1/5 ,相比于其他流行框架Mybatis源碼無疑是學習成本最低的,當做年輕人看的第一個框架源碼,無疑是非常好的。

整體架構

對于一個陌生的事物切勿一頭扎進細節里,我們先要觀其大概看看架構脈絡,MyBatis 分為三層架構,分別是基礎支撐層、核心處理層和接口層。

Mybatis原理及源碼分析

Mybatis 整體架構

基礎支撐層

基礎支撐層是這個Mybatis框架的基建,為整個Mybatis框架提供非常基礎的功能。(篇幅有限下面我們只對部分模塊做簡單的分析)

1.類型轉換模塊,我們在Mybatis中使用< typeAliase >標簽定義一個別名就是使用類型轉換模塊實現的。類型轉換模塊最重要的功能還是實現了Mybatis中JDBC類型和Java類型之間的轉換。主要體現在:

  • 在SQL模板綁定用戶參入實參的場景中,將Java類型轉換成JDBC類型
  • 在結果集中,將JDBC類型轉換成Java類型。

Mybatis原理及源碼分析

Mybatis類型轉換

2.日志模塊,產生日志,定位異常。

3.反射工具,對原生的Java反射作了一些封裝。

4.Binding模塊,我們在執行Mybatis中的方法時都是通過SqlSession來獲Mapper接口中的代理,這個代理將Mapper.xml文件中SQL進行關聯就是通過Binding模塊來實現的。值得注意點是這個過程是發生在編譯期。可以將錯誤提前到編譯期。

5.數據源模塊,數據源對于一個ORM來說算是非常核心的組件之一了。Mybatis默認的數據源是非常出色的,Mybatis同時也支持集成第三方的數據源。

6.緩存模塊,緩存模塊的好壞直接影響這個ORM的性能。Mybatis提供了兩級緩存,同時也支持第三方緩存中間件集成。

Mybatis原理及源碼分析

Mybatis緩存

7.解析器模塊,主要是config.xml配置文件解析,和mapper.xml文件解析。

8.事務管理模塊,事務模塊對數據庫的事務機制進行控制,對數據庫事務進行了抽象,同時也對spring框架進行了整合。詳細的處理邏輯下文會結合源碼詳細解析。

核心處理層

核心處理層是我們在學習Mybatis原理的時候需要花80%時間的地方。核心處理層是 MyBatis 核心實現所在,其中涉及 MyBatis 的初始化以及執行一條 SQL 語句的全流程。

配置解析

MyBatis 的初始化以及執行一條 SQL 語句的全流程中也包含了配置解析,我們在現實開發中一般都是使用spring boot starter的自動配置。我們一項目啟動為起點一層一層剝開Mybatis的流程。先打開org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration首先明確一點就是MybatisAutoConfiguration的目的就是要得到一個SqlSessionFactory。

  1. @Bean 
  2. @ConditionalOnMissingBean 
  3. public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { 
  4.   SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); 
  5.   factory.setDataSource(dataSource); 
  6.   factory.setVfs(SpringBootVFS.class); 
  7.   if (StringUtils.hasText(this.properties.getConfigLocation())) { 
  8.     factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation())); 
  9.   } 
  10.   Configuration configuration = this.properties.getConfiguration(); 
  11.   if (configuration == null && !StringUtils.hasText(this.properties.getConfigLocation())) { 
  12.     configuration = new Configuration(); 
  13.   } 
  14.   if (configuration != null && !CollectionUtils.isEmpty(this.configurationCustomizers)) { 
  15.     for (ConfigurationCustomizer customizer : this.configurationCustomizers) { 
  16.       customizer.customize(configuration); 
  17.     } 
  18.   } 
  19.   factory.setConfiguration(configuration); 
  20.   if (this.properties.getConfigurationProperties() != null) { 
  21.     factory.setConfigurationProperties(this.properties.getConfigurationProperties()); 
  22.   } 
  23.   if (!ObjectUtils.isEmpty(this.interceptors)) { 
  24.     factory.setPlugins(this.interceptors); 
  25.   } 
  26.   if (this.databaseIdProvider != null) { 
  27.     factory.setDatabaseIdProvider(this.databaseIdProvider); 
  28.   } 
  29.   if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) { 
  30.     factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage()); 
  31.   } 
  32.   if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) { 
  33.     factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage()); 
  34.   } 
  35.   if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) { 
  36.     factory.setMapperLocations(this.properties.resolveMapperLocations()); 
  37.   } 
  38.  
  39.   return factory.getObject(); 

這里是通過MybatisProperties里面的配置并放入到SqlSessionFactoryBean中,再由SqlSessionFactoryBean得到SqlSessionFactory。看到最后一行return factory.getObject();我們進去看看這個factory.getObject()的邏輯是如何得到一個SqlSessionFactory。

  1. @Override 
  2. public SqlSessionFactory getObject() throws Exception { 
  3.   if (this.sqlSessionFactory == null) { 
  4.     afterPropertiesSet(); 
  5.   } 
  6.  
  7.   return this.sqlSessionFactory; 

這一步沒什么好說的,看看afterPropertiesSet()方法

  1. @Override 
  2. public void afterPropertiesSet() throws Exception { 
  3.   notNull(dataSource, "Property 'dataSource' is required"); 
  4.   notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required"); 
  5.   state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null), 
  6.             "Property 'configuration' and 'configLocation' can not specified with together"); 
  7.  
  8.   this.sqlSessionFactory = buildSqlSessionFactory(); 

重點來了,看看這個buildSqlSessionFactory()方法這里的核心目的就是將configurationProperties解析到Configuration對象中。代碼太長了我就不貼出來了, buildSqlSessionFactory()的邏輯我畫了個圖,有興趣的小伙伴自行看一下。

Mybatis原理及源碼分析

Mybatis配置解析1

我們不要陷入細節之中,我們看看中點看看buildSqlSessionFactory() 方法的最后一行this.sqlSessionFactoryBuilder.build(configuration)點進去

  1. public SqlSessionFactory build(Configuration config) { 
  2.     return new DefaultSqlSessionFactory(config); 
  3.   } 

通過buildSqlSessionFactory()解析得到的Configuration對象創建一個DefaultSqlSessionFactory(config),到此我們就得到了SqlSessionFactory同時被配置成一個bean了。

我們最終操作都是SqlSession,什么時候會通過SqlSessionFactory得到一個SqlSession呢?

要解決這個問題我們回到最開始的MybatisAutoConfiguration的sqlSessionTemplate(SqlSessionFactory sqlSessionFactory)這個方法,點開SqlSessionTemplate發現它是一個實現了SqlSession到這里我們猜測就是在這里SqlSessionFactory會構建一個SqlSession出來。我們進入new SqlSessionTemplate(sqlSessionFactory)看看源碼。

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

再往下看,我們就看到了

  1. public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType, 
  2.     PersistenceExceptionTranslator exceptionTranslator) { 
  3.  
  4.   notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required"); 
  5.   notNull(executorType, "Property 'executorType' is required"); 
  6.  
  7.   this.sqlSessionFactory = sqlSessionFactory; 
  8.   this.executorType = executorType; 
  9.   this.exceptionTranslator = exceptionTranslator; 
  10.   this.sqlSessionProxy = (SqlSession) newProxyInstance( 
  11.       SqlSessionFactory.class.getClassLoader(), 
  12.       new Class[] { SqlSession.class }, 
  13.       new SqlSessionInterceptor()); 

這里通過動態代理創建了一個SqlSession。

參數映射、SQL解析

我們先看一下MapperFactoryBean類,這個類實現了FactoryBean在bean初始化的時候會調用getObject()方法我們看看這個類下重寫的getObject()方法里的內容。

  1. @Override 
  2.  public T getObject() throws Exception { 
  3.    return getSqlSession().getMapper(this.mapperInterface); 
  4.  } 

這里調用了sqlSession的getMapper()方法。一層一層點進去里面返回的是一個代理對象。最后的執行是由MapperProxy執行。

  1. public <T> T getMapper(Class<T> type, SqlSession sqlSession) { 
  2.     final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type); 
  3.     if (mapperProxyFactory == null) { 
  4.       throw new BindingException("Type " + type + " is not known to the MapperRegistry."); 
  5.     } 
  6.     try { 
  7.       return mapperProxyFactory.newInstance(sqlSession); 
  8.     } catch (Exception e) { 
  9.       throw new BindingException("Error getting mapper instance. Cause: " + e, e); 
  10.     } 
  11.   } 

接下來的流程我還是畫個流程圖,防止小伙伴們走丟。我這里的內容可能未必完全和小標題一樣,我主要按照sql執行的流程講解的。

Mybatis原理及源碼分析

Mybatis參數綁定

先看一下MapperProxy中的invoke方法,cachedMapperMethod()方法將MapperMethod緩存起來了。

  1. @Override 
  2. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 
  3.   try { 
  4.     if (Object.class.equals(method.getDeclaringClass())) { 
  5.       return method.invoke(this, args); 
  6.     } else if (isDefaultMethod(method)) { 
  7.       return invokeDefaultMethod(proxy, method, args); 
  8.     } 
  9.   } catch (Throwable t) { 
  10.     throw ExceptionUtil.unwrapThrowable(t); 
  11.   } 
  12.   final MapperMethod mapperMethod = cachedMapperMethod(method); 
  13.   return mapperMethod.execute(sqlSession, args); 
  14.  
  15.  private MapperMethod cachedMapperMethod(Method method) { 
  16.     MapperMethod mapperMethod = methodCache.get(method); 
  17.     if (mapperMethod == null) { 
  18.       mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()); 
  19.       methodCache.put(method, mapperMethod); 
  20.     } 
  21.     return mapperMethod; 
  22.   } 

我們在往下看mapperMethod.execute(sqlSession, args)方法。

  1. public Object execute(SqlSession sqlSession, Object[] args) { 
  2.   Object result; 
  3.   switch (command.getType()) { 
  4.     case INSERT: { 
  5.     Object param = method.convertArgsToSqlCommandParam(args); 
  6.       result = rowCountResult(sqlSession.insert(command.getName(), param)); 
  7.       break; 
  8.     } 
  9.     case UPDATE: { 
  10.       Object param = method.convertArgsToSqlCommandParam(args); 
  11.       result = rowCountResult(sqlSession.update(command.getName(), param)); 
  12.       break; 
  13.     } 
  14.     case DELETE: { 
  15.       Object param = method.convertArgsToSqlCommandParam(args); 
  16.       result = rowCountResult(sqlSession.delete(command.getName(), param)); 
  17.       break; 
  18.     } 
  19.     case SELECT
  20.       if (method.returnsVoid() && method.hasResultHandler()) { 
  21.         executeWithResultHandler(sqlSession, args); 
  22.         result = null
  23.       } else if (method.returnsMany()) { 
  24.         result = executeForMany(sqlSession, args); 
  25.       } else if (method.returnsMap()) { 
  26.         result = executeForMap(sqlSession, args); 
  27.       } else if (method.returnsCursor()) { 
  28.         result = executeForCursor(sqlSession, args); 
  29.       } else { 
  30.         Object param = method.convertArgsToSqlCommandParam(args); 
  31.         result = sqlSession.selectOne(command.getName(), param); 
  32.       } 
  33.       break; 
  34.     case FLUSH: 
  35.       result = sqlSession.flushStatements(); 
  36.       break; 
  37.     default
  38.       throw new BindingException("Unknown execution method for: " + command.getName()); 
  39.   } 
  40.   if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) { 
  41.     throw new BindingException("Mapper method '" + command.getName()  
  42.         + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ")."); 
  43.   } 
  44.   return result; 

method.convertArgsToSqlCommandParam(args)這里就是處理參數轉換的邏輯。還有很多細節由于篇幅有限以及時間倉促我們不做過多的贅述,感興趣的小伙伴可以結合上面的圖自己看看。下面我們看SQL的執行流程是怎么樣的。整體流程如下圖。

Mybatis原理及源碼分析

Mybatis執行流程

我們就不對每一個執行器都分析,我只挑一個SimpleExecutor來具體跟一下源碼。我們還是先看看圖吧,防止自己把自己搞蒙。

Mybatis原理及源碼分析

以simpleExecutor為例的執行流程

  1. @Override 
  2. public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException { 
  3.   Statement stmt = null
  4.   try { 
  5.     Configuration configuration = ms.getConfiguration(); 
  6.     StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql); 
  7.     stmt = prepareStatement(handler, ms.getStatementLog()); 
  8.     return handler.<E>query(stmt, resultHandler); 
  9.   } finally { 
  10.     closeStatement(stmt); 
  11.   } 

這里獲取了Configuration,創建了一個StatementHandler,預處理操作,具體執行的根據創建的預處理方法,最后執行query方法

  1. @Override 
  2. public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException { 
  3.   String sql = boundSql.getSql(); 
  4.   statement.execute(sql); 
  5.   return resultSetHandler.<E>handleResultSets(statement); 

到此我們整理了整個Mybatis的執行流程,分析了其中的源碼,由于篇幅有限很多地方都沒有細致的分析,但是也貼出了圖,希望能幫助到你。

原文鏈接:https://mp.weixin.qq.com/s/FWGaPN9PV9gcagHS5VyPQA

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 极品丝袜乱系列在线阅读 | 亚洲国产综合精品 | 草莓视频网站18勿进 | 精品亚洲视频在线观看 | 波多野结衣被绝伦强在线观看 | 2023最新伦理片| 日韩性事 | 四虎影视884aa·com | 四虎影视免费观看 | 操操久久| 日噜噜| 火影忍者小南裸羞羞漫画 | 国内精品久久久久影院嫩草 | 欧美成人香蕉在线观看 | 欧美一区二区三区gg高清影视 | 91精品国产高清久久久久 | 男人疯狂进女人下部视频动漫 | 人体欣赏孕妇季玥图片 | 亚洲国产精品自在在线观看 | 国产精品视频第一区二区三区 | 久久黄色免费 | 亚洲欧美日本在线观看 | 粉嫩极品国产在线观看免费 | 国产亚洲精品aaa大片 | 久久三级视频 | 国产在线视频福利 | 亚洲视频男人的天堂 | 免费看国产一级特黄aa大片 | 亚洲 欧美 日韩 综合 | 好吊日在线 | 成熟女人50岁一级毛片不卡 | 日产中文乱码卡一卡二 | 我在厨房摸岳的乳HD在线观看 | 亚洲国产成人精品无码区5566 | 亚洲午夜小视频 | 青草网址 | 精新精新国产自在现拍 | 2021精品国夜夜天天拍拍 | 插鸡视频在线观看 | 丝瓜污污 | 日本色频 |