您好,登錄后才能下訂單哦!
這篇文章主要講解了“如何理解Mybatis初始化”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“如何理解Mybatis初始化”吧!
Mybatis 初始化是由SqlSessionFactoryBuilder
來完成的,主要的工作解析XML文件,并將解析的類容封裝到Configuration
類中,最后將Configuration
類封裝到SqlSessionFactory
中并返回,自此初始化完成。
完成對XML文件解析的是XMLConfigBuilder
、XMLMapperBuilder
、XMLStatementBuilder
三個類來完成:
XMLConfigBuilder:負責全局配置文件(mybatis-config.xml)中除了mappers
節點的解析。
XMLMapperBuilder:負責解析xxxMapper.xml
映射文件中cache-ref
、cache
、parameterMap
、resultMap
、sql
節點;根據 namespace 將Mapper接口的動態代理工廠注冊到 MapperRegistry 中。
XMLStatementBuilder:負責解析xxxMapper.xml
映射文件中SQL語句節點,如:select
、insert
、update
、delete
。
XMLScriptBuilder:負責解析SQL腳本,然后封裝成SqlSource
。
SqlSessionFactoryBuilder會將解析任務托給XMLConfigBuilder類,源碼如下:
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) { try { // 委托給XMLConfigBuilder去解析配置文件 XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties); // 開始解析 return build(parser.parse()); } ... } public SqlSessionFactory build(Configuration config) { return new DefaultSqlSessionFactory(config); }
負責全局配置文件(mybatis-config.xml)中除了mappers節點的解析。解析<mappers>節點委托給XMLMapperBuilder解析器。
private void parseConfiguration(XNode root) { try { //issue #117 read properties first // 解析<properties>節點 propertiesElement(root.evalNode("properties")); // 解析<settings>節點 Properties settings = settingsAsProperties(root.evalNode("settings")); loadCustomVfs(settings); loadCustomLogImpl(settings); // 解析<typeAliases>節點 typeAliasesElement(root.evalNode("typeAliases")); pluginElement(root.evalNode("plugins")); objectFactoryElement(root.evalNode("objectFactory")); objectWrapperFactoryElement(root.evalNode("objectWrapperFactory")); reflectorFactoryElement(root.evalNode("reflectorFactory")); settingsElement(settings); // read it after objectFactory and objectWrapperFactory issue #631 environmentsElement(root.evalNode("environments")); databaseIdProviderElement(root.evalNode("databaseIdProvider")); typeHandlerElement(root.evalNode("typeHandlers")); // 解析<mappers>節點 mapperElement(root.evalNode("mappers")); } catch (Exception e) { throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e); } } private void mapperElement(XNode parent) throws Exception { if (parent != null) { for (XNode child : parent.getChildren()) { if ("package".equals(child.getName())) { String mapperPackage = child.getStringAttribute("name"); configuration.addMappers(mapperPackage); } else { String resource = child.getStringAttribute("resource"); String url = child.getStringAttribute("url"); String mapperClass = child.getStringAttribute("class"); if (resource != null && url == null && mapperClass == null) { ErrorContext.instance().resource(resource); InputStream inputStream = Resources.getResourceAsStream(resource); // 委托XMLMapperBuilder來解析映射文件 XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments()); mapperParser.parse(); } else if (resource == null && url != null && mapperClass == null) { ErrorContext.instance().resource(url); InputStream inputStream = Resources.getUrlAsStream(url); // 委托XMLMapperBuilder來解析映射文件 XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments()); mapperParser.parse(); } else if (resource == null && url == null && mapperClass != null) { Class<?> mapperInterface = Resources.classForName(mapperClass); configuration.addMapper(mapperInterface); } else { throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one."); } } } } }
負責解析xxxMapper.xml映射文件中cache-ref、cache、parameterMap、resultMap、sql節點;根據 namespace 將Mapper接口的動態代理工廠(MapperProxyFactory)注冊到 MapperRegistry 中。
public void parse() { // 防止重復解析 if (!configuration.isResourceLoaded(resource)) { // 解析xxxMapper.xml 映射文件中的 mapper節點 configurationElement(parser.evalNode("/mapper")); // 標記為已經加載過 configuration.addLoadedResource(resource); // 根據 namespace 將Mapper接口的動態代理工廠注冊到 MapperRegistry 中 bindMapperForNamespace(); } // 兜底 parsePendingResultMaps(); parsePendingCacheRefs(); parsePendingStatements(); } private void configurationElement(XNode context) { try { String namespace = context.getStringAttribute("namespace"); if (namespace == null || namespace.equals("")) { throw new BuilderException("Mapper's namespace cannot be empty"); } builderAssistant.setCurrentNamespace(namespace); // 解析<cache-ref>節點 cacheRefElement(context.evalNode("cache-ref")); // 解析<cache>節點 cacheElement(context.evalNode("cache")); // 解析<parameterMap>節點 parameterMapElement(context.evalNodes("/mapper/parameterMap")); // 解析<resultMap>節點 resultMapElements(context.evalNodes("/mapper/resultMap")); sqlElement(context.evalNodes("/mapper/sql")); // 解析<select|insert|update|delete>節點 buildStatementFromContext(context.evalNodes("select|insert|update|delete")); } catch (Exception e) { throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e); } } private void buildStatementFromContext(List<XNode> list) { if (configuration.getDatabaseId() != null) { buildStatementFromContext(list, configuration.getDatabaseId()); } buildStatementFromContext(list, null); } private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) { for (XNode context : list) { // 解析<select|insert|update|delete>節點委托給 XMLStatementBuilder final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId); try { statementParser.parseStatementNode(); } catch (IncompleteElementException e) { configuration.addIncompleteStatement(statementParser); } } }
負責解析xxxMapper.xml映射文件中SQL語句節點,如:select、insert、update、delete。解析<select|insert|update|delete>節點委托給XMLStatementBuilder解析器。
public void parseStatementNode() { String id = context.getStringAttribute("id"); String databaseId = context.getStringAttribute("databaseId"); if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) { return; } // 根據節點的名稱來判斷SQL語句的類型(select|insert|update|delete) String nodeName = context.getNode().getNodeName(); SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH)); boolean isSelect = sqlCommandType == SqlCommandType.SELECT; boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect); boolean useCache = context.getBooleanAttribute("useCache", isSelect); boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false); // Include Fragments before parsing // 解析<include>節點 XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant); includeParser.applyIncludes(context.getNode()); String parameterType = context.getStringAttribute("parameterType"); Class<?> parameterTypeClass = resolveClass(parameterType); String lang = context.getStringAttribute("lang"); LanguageDriver langDriver = getLanguageDriver(lang); // Parse selectKey after includes and remove them. // 解析<selectKey>節點,并在XML中刪除<selectKey>節點 processSelectKeyNodes(id, parameterTypeClass, langDriver); // Parse the SQL (pre: <selectKey> and <include> were parsed and removed) KeyGenerator keyGenerator; String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX; keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true); if (configuration.hasKeyGenerator(keyStatementId)) { keyGenerator = configuration.getKeyGenerator(keyStatementId); } else { keyGenerator = context.getBooleanAttribute("useGeneratedKeys", configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType)) ? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE; } // 解析SQL語句,然后封裝成SqlSource SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass); StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString())); Integer fetchSize = context.getIntAttribute("fetchSize"); Integer timeout = context.getIntAttribute("timeout"); String parameterMap = context.getStringAttribute("parameterMap"); String resultType = context.getStringAttribute("resultType"); Class<?> resultTypeClass = resolveClass(resultType); String resultMap = context.getStringAttribute("resultMap"); String resultSetType = context.getStringAttribute("resultSetType"); ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType); if (resultSetTypeEnum == null) { resultSetTypeEnum = configuration.getDefaultResultSetType(); } String keyProperty = context.getStringAttribute("keyProperty"); String keyColumn = context.getStringAttribute("keyColumn"); String resultSets = context.getStringAttribute("resultSets"); // 使用建造者模式構建MappedStatement對象 builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass, resultSetTypeEnum, flushCache, useCache, resultOrdered, keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets); }
Configuration
其實就是XML配置文件的Java形態,Configuration是單例的,生命周期是應用級的;
對應xxxMapper.xml映射文件中的resultMap
節點。<resultMap>
節點中的子節點使用ResultMapping
來封裝,如:<id>
、<result>
等節點。
對應xxxMapper.xml映射文件中的<select>
、<insert>
、<update>
和<delete>
節點。
對應xxxMapper.xml映射文件中的sql語句,經過解析SqlSource包含的語句最終僅僅包含?占位符,可以直接提交給數據庫執行;
它是Mapper接口動態代理工廠類的注冊中心。在MyBatis中,通過MapperProxy實現InvocationHandler接口,通過MapperProxyFactory生成動態代理的實例對象;
Mybatis的整個初始化過程使用了建造者模式。建造者模式比較適合生成復雜對象,主要關注對象的實例化具體細節。
https://github.com/xiaolyuh/mybatis
感謝各位的閱讀,以上就是“如何理解Mybatis初始化”的內容了,經過本文的學習后,相信大家對如何理解Mybatis初始化這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。