一、前言
不知道大家有没有遇到过这种需求,比如现在有一个 mapper 标签:
<selectid="query"resultType="HashMap">
${sql}</select>
很显然,这个标签的作用就是直接执行传入的拼接好的 SQL 语句,比如:
select*fromtablewhere condition
一般情况下,这个 SQL 的条件是我们手动拼接好的。那么如果我们直接让 mybatis 帮我们拼接会怎么样呢?比如假设我们传来的 SQL 是这样的:
select*fromtable<where><if test="condition">and condition</if></where>
那么 mybatis 能不能正确解析并执行呢?
答案是否定的!
因为 mybatis 是在启动的时就已经解析好了全部的 mapper 标签,而不是运行时解析,所以上述例子并不能正确执行。
但是我们想让它能够运行要怎么办呢?那就只有我们自己手动去解析了!
二、动态解析 mapper 标签
1、寻找解析方法
想要动态的解析 mapper 标签,别无他法,只能从源码入手,看看官方是怎么解析的,然后照猫画虎。下面就看看 mybatis 是怎么做的:
首先,毫无疑问从 SqlSessionFactoryBuilder.java 入手:
public SqlSessionFactorybuild(InputStream inputStream, String environment, Properties properties){try{
XMLConfigBuilder parser=newXMLConfigBuilder(inputStream, environment, properties);returnbuild(parser.parse());}catch(Exception e){throw ExceptionFactory.wrapException("Error building SqlSession.", e);}finally{
ErrorContext.instance().reset();try{
inputStream.close();}catch(IOException e){// Intentionally ignore. Prefer previous error.}}}
可以看到其实是创建了一个 XMLConfigBuilder 对象,让它来进行解析,跟进去看一下它的 parse 方法:
public Configurationparse(){if(parsed){thrownewBuilderException("Each XMLConfigBuilder can only be used once.");}
parsed=true;parseConfiguration(parser.evalNode("/configuration"));return configuration;}
里面又调了 parseConfiguration 方法,再跟:
privatevoidparseConfiguration(XNode root){try{//issue #117 read properties firstpropertiesElement(root.evalNode("properties"));
Properties settings=settingsAsProperties(root.evalNode("settings"));loadCustomVfs(settings);loadCustomLogImpl(settings);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 #631environmentsElement(root.evalNode("environments"));databaseIdProviderElement(root.evalNode("databaseIdProvider"));typeHandlerElement(root.evalNode("typeHandlers"));mapperElement(root.evalNode("mappers"));}catch(Exception e){thrownewBuilderException("Error parsing SQL Mapper Configuration. Cause: "+ e, e);}}
这个方法好长,我也看不懂,但我看到了最后一行有个方法 mapperElement,有点怀疑,跟进去:
privatevoidmapperElement(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 mapperParser=newXMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperParser.parse();}elseif(resource== null&& url!= null&& mapperClass== null){
ErrorContext.instance().resource(url);
InputStream inputStream= Resources.getUrlAsStream(url);
XMLMapperBuilder mapperParser=newXMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
mapperParser.parse();}elseif(resource== null&& url== null&& mapperClass!= null){
Class<?> mapperInterface= Resources.classForName(mapperClass);
configuration.addMapper(mapperInterface);}else{thrownewBuilderException("A mapper element may only specify a url, resource or class, but not more than one.");}}}}}
又是一个好长的方法,不过仔细看看里面有一个对象很显眼 XMLMapperBuilder,看名字就知道就是它的,看看它的 parse 方法:
publicvoidparse(){if(!configuration.isResourceLoaded(resource)){configurationElement(parser.evalNode("/mapper"));
configuration.addLoadedResource(resource);bindMapperForNamespace();}parsePendingResultMaps();parsePendingCacheRefs();parsePendingStatements();}
从这段代码中,我一眼就看出第三行是开始解析 mapper 标签了,跟进去:
privatevoidconfigurationElement(XNode context){try{
String namespace= context.getStringAttribute("namespace");if(namespace== null|| namespace.equals("")){thrownewBuilderException("Mapper's namespace cannot be empty");}
builderAssistant.setCurrentNamespace(namespace);cacheRefElement(context.evalNode("cache-ref"));cacheElement(context.evalNode("cache"));parameterMapElement(context.evalNodes("/mapper/parameterMap"));resultMapElements(context.evalNodes("/mapper/resultMap"));sqlElement(context.evalNodes("/mapper/sql"));buildStatementFromContext(context.evalNodes("select|insert|update|delete"));}catch(Exception e){thrownewBuilderException("Error parsing Mapper XML. The XML location is '"+ resource+"'. Cause: "+ e, e);}}
不知道为啥,看到 “select|insert|update|delete” 我就感觉越来越接近真相,跟:
privatevoidbuildStatementFromContext(List<XNode> list){if(configuration.getDatabaseId()!= null){buildStatementFromContext(list, configuration.getDatabaseId());}buildStatementFromContext(list, null);}
就这?真不知道加判断干嘛,直接调嘛,获取不到自然就是空,我估计是为了可读性,赞一个!接着跟:
privatevoidbuildStatementFromContext(List<XNode> list, String requiredDatabaseId){for(XNode context: list){final XMLStatementBuilder statementParser=newXMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);try{
statementParser.parseStatementNode();}catch(IncompleteElementException e){
configuration.addIncompleteStatement(statementParser);}}}
废话不说,直接跟:
publicvoidparseStatementNode(){
String id= context.getStringAttribute("id");
String databaseId= context.getStringAttribute("databaseId");if(!databaseIdMatchesCurrent(id, databaseId,this.requiredDatabaseId)){return;}
Integer fetchSize= context.getIntAttribute("fetchSize");
Integer timeout= context.getIntAttribute("timeout");
String parameterMap= context.getStringAttribute("parameterMap");
String parameterType= context.getStringAttribute("parameterType");
Class<?> parameterTypeClass=resolveClass(parameterType);
String resultMap= context.getStringAttribute("resultMap");
String resultType= context.getStringAttribute("resultType");
String lang= context.getStringAttribute("lang");
LanguageDriver langDriver=getLanguageDriver(lang);
Class<?> resultTypeClass=resolveClass(resultType);
String resultSetType= context.getStringAttribute("resultSetType");
StatementType statementType= StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
ResultSetType resultSetTypeEnum=resolveResultSetType(resultSetType);
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
XMLIncludeTransformer includeParser=newXMLIncludeTransformer(configuration, builderAssistant);
includeParser.applyIncludes(context.getNode());// Parse selectKey after includes and remove them.processSelectKeyNodes(id, parameterTypeClass, langDriver);// Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
SqlSource sqlSource= langDriver.createSqlSource(configuration, context, parameterTypeClass);
String resultSets= context.getStringAttribute("resultSets");
String keyProperty= context.getStringAttribute("keyProperty");
String keyColumn= context.getStringAttribute("keyColumn");
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;}
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);}
这。。。就是真相吧~~~
好吧,其实到这里就可以了,因为已经开始解析了。下面我们就想办法看看怎么能调到这个方法,那么毫无疑问,我们回退一步:
privatevoidbuildStatementFromContext(List<XNode> list, String requiredDatabaseId){for(XNode context: list){final XMLStatementBuilder statementParser=newXMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);try{
statementParser.parseStatementNode();}catch(IncompleteElementException e){
configuration.addIncompleteStatement(statementParser);}}}
很明显,我们需要一个 XMLStatementBuilder 对象,而这个对象又需要 Configuration、MapperBuilderAssistant、XNode、requiredDatabaseId。
而我们动态解析一个 mapper 肯定是基于一个我们自己配置的已经存在的 SqlSessionFactory 的,所以 Configuration、requiredDatabaseId 我们都可以通过 SqlSessionFactory 获取到。
那么还有两个参数,先看 MapperBuilderAssistant:
它是 XMLMapperBuilder 的一个属性,MapperBuilderAssistant 正是在实例化 XMLMapperBuilder 的时候被创建的,看一下 XMLMapperBuilder 的构造方法:
publicXMLMapperBuilder(InputStream inputStream, Configuration configuration, String resource, Map<String, XNode> sqlFragments){this(newXPathParser(inputStream,true, configuration.getVariables(),newXMLMapperEntityResolver()),
configuration, resource, sqlFragments);}privateXMLMapperBuilder(XPathParser parser, Configuration configuration, String resource, Map<String, XNode> sqlFragments){super(configuration);this.builderAssistant=newMapperBuilderAssistant(configuration, resource);this.parser= parser;this.sqlFragments= sqlFragments;this.resource= resource;}
可以看到创建 MapperBuilderAssistant 只需要两个参数,configuration、resource。
其中 Configuration 已不是问题,而 resource 呢,更简单了,它正是我们的 mapper 标签字符串!
再看 XNode:
细心的同学应该会注意到,前面的代码中很多地方都有一个 evalNode 方法,这个方法正是解析 xml 节点的方法,也就是说 XNode 对象就是 mapper 标签作为 xml 节点被解析后的对象!
终于可以看到最终结果代码了!
2、实现动态解析
直接上代码:
/**
*
* @param sqlSessionFactory sqlSessionFactory
* @param executeClass 执行动态 mapper 的代理接口类
* @param xml mapper 标签,比如:<select id="dynamicQuery">select * from table</select>
* @param nodeType mapper 节点类型,比如:/select
*/publicvoiddynamicParse(SqlSessionFactory sqlSessionFactory, Class<?> executeClass, String xml, String nodeType){
Configuration configuration= sqlSessionFactory.getConfiguration();
MapperBuilderAssistant mapperBuilderAssistant=newMapperBuilderAssistant(configuration, xml);
mapperBuilderAssistant.setCurrentNamespace(executeClass.getName());
XNode xNode=newXPathParser(xml).evalNode(nodeType);
XMLStatementBuilder xmlStatementBuilder=newXMLStatementBuilder(configuration, mapperBuilderAssistant, xNode, configuration.getDatabaseId());try{
xmlStatementBuilder.parseStatementNode();}catch(IncompleteElementException e){/**
* 这里值得注意,此异常是元素不完整异常,应该是 mapper 中存在元素依赖导致的
* 官方是先保存起来,后面再解析一次,保存代码如下所示:
* this.configuration.addIncompleteStatement(xmlStatementBuilder);
*
* 再次解析的方法是:
* parsePendingStatements();
*
* 这里就直接抛异常了
*/thrownewRuntimeException();}}}
完结散花!