自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

又是搞砸Mybatis源碼的一天

開發(fā)
源碼一章肯定是講不完的,所以阿粉會分成幾個章節(jié),并且講源碼的話,代碼肯定比較多,比較干,所以請大家事先準備好開水哦.

1.上期回顧

前面初識 mybatis 章節(jié),阿粉首先搭建了一個簡單的項目,只用了 mybatis 的 jar 包。然后通過一個測試代碼,講解了幾個重要的類和步驟。

先看下這個測試類:

  1. public class MybatisTest { 
  2.     @Test 
  3.     public void testSelect() throws IOException { 
  4.         String resource = "mybatis-config.xml"
  5.         InputStream inputStream = Resources.getResourceAsStream(resource); 
  6.         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 
  7.         SqlSession session = sqlSessionFactory.openSession(); 
  8.         try { 
  9.             FruitMapper mapper = session.getMapper(FruitMapper.class); 
  10.             Fruit fruit = mapper.findById(1L); 
  11.             System.out.println(fruit); 
  12.         } finally { 
  13.             session.close(); 
  14.         } 
  15.     } 

這章的話,阿粉會帶著大家理解一下源碼,基于上面測試的代碼。阿粉先申明一下,源碼一章肯定是講不完的,所以阿粉會分成幾個章節(jié),并且講源碼的話,代碼肯定比較多,比較干,所以請大家事先準備好開水哦。

2.源碼分析

這里阿粉會根據 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream) 這段代碼來分析 mybatis 做了哪些事情。

2.1設計模式

通過這段代碼,我們首先分析一下用到了哪些設計模式呢?

首先 SqlSessionFactory 這個類用到了工廠模式,并且上一章阿粉也說到了,這個類是全局唯一的,所以它還使用了單列模式。

然后是 SqlSessionFactoryBuilder 這個類,一看就知道用到了建造者模式。

所以,只看這段代碼就用到了工廠模式,單列模式和建造者模式。

2.2mybatis做了什么事情

這里就開始源碼之旅了,首先 ctrl + 左鍵點擊 build 方法,我們會看到

  1. public SqlSessionFactory build(InputStream inputStream) { 
  2.    return build(inputStream, nullnull); 
  3.  } 

再點擊 build ,然后就是

  1. public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) { 
  2.     try { 
  3.       XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties); 
  4.       return build(parser.parse()); 
  5.         //后面代碼省略 
  6.         ... 
  7.     } 

首先 XMLConfigBuilder 這個類就是用來解析我們的配置文件 mybatis-config.xml ,調用這個類的構造函數,主要是創(chuàng)建一個 Configuration 對象,這個對象的屬性就對應mybatis-config.xml里面的一級標簽。這里不貼代碼,有興趣的自己點開看下。

然后就是 build(parser.parse()) 這段代碼,先執(zhí)行 parse()方法,再執(zhí)行 build() 方法。不過這里,阿粉先說下 build() 這個方法,首先parse() 方法返回的就是 Configuration 對象,然后我們點擊 build 

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

這里就是返回的默認的SqlSessionFactory 。

然后我們再說 parse() 方法,因為這個是核心方法。我們點進去看下。 

  1. public Configuration parse() { 
  2.     if (parsed) { 
  3.       throw new BuilderException("Each XMLConfigBuilder can only be used once."); 
  4.     } 
  5.     parsed = true
  6.     parseConfiguration(parser.evalNode("/configuration")); 
  7.     return configuration; 
  8.   } 

首先是 if 判斷,就是防止解析多次???parseConfiguration方法。

  1. private void parseConfiguration(XNode root) { 
  2.     try { 
  3.       //issue #117 read properties first 
  4.       propertiesElement(root.evalNode("properties")); 
  5.       Properties settings = settingsAsProperties(root.evalNode("settings")); 
  6.       loadCustomVfs(settings); 
  7.       loadCustomLogImpl(settings); 
  8.       typeAliasesElement(root.evalNode("typeAliases")); 
  9.       pluginElement(root.evalNode("plugins")); 
  10.       objectFactoryElement(root.evalNode("objectFactory")); 
  11.       objectWrapperFactoryElement(root.evalNode("objectWrapperFactory")); 
  12.       reflectorFactoryElement(root.evalNode("reflectorFactory")); 
  13.       settingsElement(settings); 
  14.       // read it after objectFactory and objectWrapperFactory issue #631 
  15.       environmentsElement(root.evalNode("environments")); 
  16.       databaseIdProviderElement(root.evalNode("databaseIdProvider")); 
  17.       typeHandlerElement(root.evalNode("typeHandlers")); 
  18.       mapperElement(root.evalNode("mappers")); 
  19.     } catch (Exception e) { 
  20.       throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e); 
  21.     } 
  22.   } 

這里就開始了解析mybatis-config.xml里面的一級標簽了。阿粉不全部講,只說幾個主要的。

  1. settings:全局配置,比如我們的二級緩存,延遲加載,日志打印等
  2. mappers:解析dao層的接口和mapper.xml文件
  3. properties:這個一般是配置數據庫的信息,如:數據庫連接,用戶名和密碼等,不講
  4. typeAliases :參數和返回結果的實體類的別名,不講
  5. plugins:插件,如:分頁插件,不講
  6. objectFactory,objectWrapperFactory:實例化對象用的,比如返回結果是一個對象,就是通過這個工廠反射獲取的,不講
  7. environments:事物和數據源的配置,不講
  8. databaseIdProvider:這個是用來支持不同廠商的數據庫
  9. typeHandlers:這個是java類型和數據庫的類型做映射,比如數據庫的 varchar類型對應 java 的String 類型,不講

2.3解析settings

我們點擊 settingsElement(settings) 這個方法 

  1. private void settingsElement(Properties props) { 
  2.   configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior""PARTIAL"))); 
  3.   configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior""NONE"))); 
  4.   configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true)); 
  5.   configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory"))); 
  6.   configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false)); 
  7.   configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), false)); 
  8.   configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true)); 
  9.   configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true)); 
  10.   configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false)); 
  11.   configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType""SIMPLE"))); 
  12.   configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null)); 
  13.   configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null)); 
  14.   configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false)); 
  15.   configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false)); 
  16.   configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope""SESSION"))); 
  17.   configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull""OTHER"))); 
  18.   configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString")); 
  19.   configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true)); 
  20.   configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage"))); 
  21.   configuration.setDefaultEnumTypeHandler(resolveClass(props.getProperty("defaultEnumTypeHandler"))); 
  22.   configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false)); 
  23.   configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true)); 
  24.   configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false)); 
  25.     configuration.setLogPrefix(props.getProperty("logPrefix")); 
  26.   configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory"))); 
  27.   } 

這個就是設置我們的全局配置信息, setXXX 方法的第一個參數是 mybatis-config.xml 里面標簽里面配置的。有的同學就會問了,阿粉阿粉,我們里面沒有配置那么多啊,這里怎么設置那么多屬性,值是什么呢?那我們看下方法的第二個參數,這個就是默認值。比如 cacheEnabled 這個屬性,緩存開關,沒有配置的話,默認是開啟的 true。所有以后看全局配置的默認值,不用去官網看了,直接在這個方法里面看。

2.4解析mappers

點擊 mapperElement 方法 

  1. private void mapperElement(XNode parent) throws Exception { 
  2.     if (parent != null) { 
  3.       for (XNode child : parent.getChildren()) { 
  4.         if ("package".equals(child.getName())) { 
  5.           String mapperPackage = child.getStringAttribute("name"); 
  6.           configuration.addMappers(mapperPackage); 
  7.         } else { 
  8.           String resource = child.getStringAttribute("resource"); 
  9.           String url = child.getStringAttribute("url"); 
  10.           String mapperClass = child.getStringAttribute("class"); 
  11.           if (resource != null && url == null && mapperClass == null) { 
  12.             ErrorContext.instance().resource(resource); 
  13.             InputStream inputStream = Resources.getResourceAsStream(resource); 
  14.             XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments()); 
  15.             mapperParser.parse(); 
  16.           } else if (resource == null && url != null && mapperClass == null) { 
  17.             ErrorContext.instance().resource(url); 
  18.             InputStream inputStream = Resources.getUrlAsStream(url); 
  19.             XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments()); 
  20.             mapperParser.parse(); 
  21.           } else if (resource == null && url == null && mapperClass != null) { 
  22.             Class<?> mapperInterface = Resources.classForName(mapperClass); 
  23.             configuration.addMapper(mapperInterface); 
  24.           } else { 
  25.             throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one."); 
  26.           } 
  27.         } 
  28.       } 
  29.     } 
  30.   } 

這里有4個判斷 page (包),resource(相對路徑,阿粉配的就是這個,所有按照這個講解源碼),url(絕對路徑),class(單個接口)

XMLMapperBuilder 這個類是用來解析mapper.xml文件的。然后我們點擊 parse 方法。 

  1. public void parse() { 
  2.     if (!configuration.isResourceLoaded(resource)) { 
  3.       configurationElement(parser.evalNode("/mapper")); 
  4.       configuration.addLoadedResource(resource); 
  5.       bindMapperForNamespace(); 
  6.     } 
  7.     parsePendingResultMaps(); 
  8.     parsePendingCacheRefs(); 
  9.     parsePendingStatements(); 
  10.   } 

if 判斷是判斷 mapper 是不是已經注冊了,單個Mapper重復注冊會拋出異常。

configurationElement:解析 mapper 里面所有子標簽。 

  1. private void configurationElement(XNode context) { 
  2.     try { 
  3.       String namespace = context.getStringAttribute("namespace"); 
  4.       if (namespace == null || namespace.equals("")) { 
  5.         throw new BuilderException("Mapper's namespace cannot be empty"); 
  6.       } 
  7.       builderAssistant.setCurrentNamespace(namespace); 
  8.       cacheRefElement(context.evalNode("cache-ref")); 
  9.       cacheElement(context.evalNode("cache")); 
  10.       parameterMapElement(context.evalNodes("/mapper/parameterMap")); 
  11.       resultMapElements(context.evalNodes("/mapper/resultMap")); 
  12.       sqlElement(context.evalNodes("/mapper/sql")); 
  13.       buildStatementFromContext(context.evalNodes("select|insert|update|delete")); 
  14.     } catch (Exception e) { 
  15.       throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e); 
  16.     } 
  17.   } 

cacheRefElement:緩存

cacheElement:是否開啟二級緩存

parameterMapElement:配置的參數映射

resultMapElements:配置的結果映射

sqlElement:公用sql配置

buildStatementFromContext:解析 select|insert|update|delete 標簽,獲得 MappedStatement 對象,一個標簽一個對象

bindMapperForNamespace:把namespace對應的接口的類型和代理工廠類綁定起來。 

  1. private void bindMapperForNamespace() { 
  2.     String namespace = builderAssistant.getCurrentNamespace(); 
  3.     if (namespace != null) { 
  4.       Class<?> boundType = null
  5.       try { 
  6.         boundType = Resources.classForName(namespace); 
  7.       } catch (ClassNotFoundException e) { 
  8.         //ignore, bound type is not required 
  9.       } 
  10.       if (boundType != null) { 
  11.         if (!configuration.hasMapper(boundType)) { 
  12.           // Spring may not know the real resource name so we set a flag 
  13.           // to prevent loading again this resource from the mapper interface 
  14.           // look at MapperAnnotationBuilder#loadXmlResource 
  15.           configuration.addLoadedResource("namespace:" + namespace); 
  16.           configuration.addMapper(boundType); 
  17.         } 
  18.       } 
  19.     } 
  20.   } 

看最后 addMapper 方法

  1. public <T> void addMapper(Class<T> type) { 
  2.     if (type.isInterface()) { 
  3.       if (hasMapper(type)) { 
  4.         throw new BindingException("Type " + type + " is already known to the MapperRegistry."); 
  5.       } 
  6.       boolean loadCompleted = false
  7.       try { 
  8.         knownMappers.put(type, new MapperProxyFactory<>(type)); 
  9.         // It's important that the type is added before the parser is run 
  10.         // otherwise the binding may automatically be attempted by the 
  11.         // mapper parser. If the type is already known, it won't try. 
  12.         MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type); 
  13.         parser.parse(); 
  14.         loadCompleted = true
  15.       } finally { 
  16.         if (!loadCompleted) { 
  17.           knownMappers.remove(type); 
  18.         } 
  19.       } 
  20.     } 
  21.   } 

判斷 namespace對應的類是否是接口,然后判斷是否已經加載了這個接口,最后將namespace對應的接口和 MapperProxyFactory 放到 map 容器中。MapperProxyFactory 工廠模式,創(chuàng)建 MapperProxy 對象,這個一看就是代理對象。這個就是根據接口里面的方法獲取 mapper.xml里面對應的sql語句的關鍵所在。具體的等下次講解getMapper()源碼的時候在深入的講解。

3.時序圖  

4.總結

在這一步,我們主要完成了 config 配置文件、Mapper 文件、Mapper 接口解析。我們得到了一個最重要的對象Configuration,這里面存放了全部的配置信息,它在屬性里面還有各種各樣的容器。最后,返回了一個DefaultSqlSessionFactory,里面持有了 Configuration 的實例。

 

責任編輯:武曉燕 來源: Java極客技術
相關推薦

2019-04-28 09:56:15

程序員互聯(lián)網脫發(fā)

2021-02-03 21:15:44

Ansible系統(tǒng)運維系統(tǒng)管理員

2018-06-20 09:35:43

碼農科技開發(fā)

2012-05-16 11:47:40

Gmail郵件

2019-11-07 15:30:00

EmacsIDE

2012-08-10 22:44:52

ArchSummit

2015-10-29 11:36:45

Google技術經理程序員

2017-03-21 21:17:50

大數據數據互聯(lián)網

2024-09-18 07:50:00

超算AI

2021-05-11 09:52:13

AI 數據人工智能

2021-07-15 09:49:08

B站宕機黑客

2023-02-15 09:34:20

公共字段mybatis變量

2015-06-04 09:44:20

OpenStackIBMCisco

2015-11-04 09:58:17

OpenStack云架構師開源技術

2013-10-24 15:29:25

MacOS XOS X Maveri

2015-02-10 10:21:22

程序員

2015-07-08 09:43:22

程序員

2015-12-24 18:00:45

資深程序員

2021-05-17 08:11:44

MySQL數據庫索引

2015-07-31 10:01:55

win10使用總結
點贊
收藏

51CTO技術棧公眾號