这篇文章主要讲解了“如何理解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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。