Java Code Examples for org.apache.ibatis.parsing.XNode#getStringAttribute()

The following examples show how to use org.apache.ibatis.parsing.XNode#getStringAttribute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XMLMapperBuilder.java    From mybaties with Apache License 2.0 7 votes vote down vote up
private String processNestedResultMappings(XNode context, List<ResultMapping> resultMappings) throws Exception {
	  //处理association|collection|case
    if ("association".equals(context.getName())
        || "collection".equals(context.getName())
        || "case".equals(context.getName())) {
    	
//    	<resultMap id="blogResult" type="Blog">
//    	  <association property="author" column="author_id" javaType="Author" select="selectAuthor"/>
//    	</resultMap>
//如果不是嵌套查询
      if (context.getStringAttribute("select") == null) {
    	//则递归调用5.1 resultMapElement
        ResultMap resultMap = resultMapElement(context, resultMappings);
        return resultMap.getId();
      }
    }
    return null;
  }
 
Example 2
Source File: XMLMapperBuilder.java    From Shop-for-JavaWeb with MIT License 6 votes vote down vote up
private boolean databaseIdMatchesCurrent(String id, String databaseId,
		String requiredDatabaseId) {
	if (requiredDatabaseId != null) {
		if (!requiredDatabaseId.equals(databaseId)) {
			return false;
		}
	} else {
		if (databaseId != null) {
			return false;
		}
		// skip this fragment if there is a previous one with a not null
		// databaseId
		if (this.sqlFragments.containsKey(id)) {
			XNode context = this.sqlFragments.get(id);
			if (context.getStringAttribute("databaseId") != null) {
				return false;
			}
		}
	}
	return true;
}
 
Example 3
Source File: XMLMapperBuilder.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private void configurationElement(XNode context) {
  try {
    //1.配置namespace
    String namespace = context.getStringAttribute("namespace");
    if (namespace.equals("")) {
      throw new BuilderException("Mapper's namespace cannot be empty");
    }
    builderAssistant.setCurrentNamespace(namespace);
    //2.配置cache-ref
    cacheRefElement(context.evalNode("cache-ref"));
    //3.配置cache
    cacheElement(context.evalNode("cache"));
    //4.配置parameterMap(已经废弃,老式风格的参数映射)
    parameterMapElement(context.evalNodes("/mapper/parameterMap"));
    //5.配置resultMap(高级功能)
    resultMapElements(context.evalNodes("/mapper/resultMap"));
    //6.配置sql(定义可重用的 SQL 代码段)
    sqlElement(context.evalNodes("/mapper/sql"));
    //7.配置select|insert|update|delete TODO
    buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
  } catch (Exception e) {
    throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e);
  }
}
 
Example 4
Source File: XMLMapperBuilder.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private boolean databaseIdMatchesCurrent(String id, String databaseId, String requiredDatabaseId) {
  if (requiredDatabaseId != null) {
    if (!requiredDatabaseId.equals(databaseId)) {
      return false;
    }
  } else {
    if (databaseId != null) {
      return false;
    }
    // skip this fragment if there is a previous one with a not null databaseId
    //如果有重名的id了
    //<sql id="userColumns"> id,username,password </sql>
    if (this.sqlFragments.containsKey(id)) {
      XNode context = this.sqlFragments.get(id);
      //如果之前那个重名的sql id有databaseId,则false,否则难道true?这样新的sql覆盖老的sql???
      if (context.getStringAttribute("databaseId") != null) {
        return false;
      }
    }
  }
  return true;
}
 
Example 5
Source File: XMLMapperBuilder.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private void cacheElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type", "PERPETUAL");
      Class<? extends Cache> typeClass = typeAliasRegistry.resolveAlias(type);
      String eviction = context.getStringAttribute("eviction", "LRU");
      Class<? extends Cache> evictionClass = typeAliasRegistry.resolveAlias(eviction);
      Long flushInterval = context.getLongAttribute("flushInterval");
      Integer size = context.getIntAttribute("size");
      boolean readWrite = !context.getBooleanAttribute("readOnly", false);
      boolean blocking = context.getBooleanAttribute("blocking", false);
      //读入额外的配置信息,易于第三方的缓存扩展,例:
//    <cache type="com.domain.something.MyCustomCache">
//      <property name="cacheFile" value="/tmp/my-custom-cache.tmp"/>
//    </cache>
      Properties props = context.getChildrenAsProperties();
      //调用builderAssistant.useNewCache
      builderAssistant.useNewCache(typeClass, evictionClass, flushInterval, size, readWrite, blocking, props);
    }
  }
 
Example 6
Source File: MapperScanApplication.java    From mumu with Apache License 2.0 5 votes vote down vote up
/**
 * 加载别名
 * @param configuration
 */
private void handleTypeAlias(Configuration configuration, XNode root) {
	log.info("load alias message...........................");
	TypeAliasRegistry typeAliasRegistry = configuration.getTypeAliasRegistry();
	XNode parent = root.evalNode("typeAliases");
	if(parent!=null){
		for (XNode child : parent.getChildren()) {
			if ("package".equals(child.getName())) {
				String typeAliasPackage = child.getStringAttribute("name");
				configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
				log.info("package:"+typeAliasPackage);
			} else {
				String alias = child.getStringAttribute("alias");
				String type = child.getStringAttribute("type");
				try {
					Class<?> clazz = Resources.classForName(type);
					if (alias == null) {
						typeAliasRegistry.registerAlias(clazz);
					} else {
						typeAliasRegistry.registerAlias(alias, clazz);
					}
					log.info("alias:"+alias+"   type:"+clazz);
				} catch (ClassNotFoundException e) {
					throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
				}
			}
		}
	}
}
 
Example 7
Source File: XMLConfigBuilder.java    From QuickProject with Apache License 2.0 5 votes vote down vote up
private DataSourceFactory dataSourceElement(XNode context) throws Exception {
  if (context != null) {
    String type = context.getStringAttribute("type");
    Properties props = context.getChildrenAsProperties();
    DataSourceFactory factory = (DataSourceFactory) resolveClass(type).newInstance();
    factory.setProperties(props);
    return factory;
  }
  throw new BuilderException("Environment declaration requires a DataSourceFactory.");
}
 
Example 8
Source File: XMLConfigBuilder.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private TransactionFactory transactionManagerElement(XNode context) throws Exception {
  if (context != null) {
    String type = context.getStringAttribute("type");
    Properties props = context.getChildrenAsProperties();
//根据type="JDBC"解析返回适当的TransactionFactory
    TransactionFactory factory = (TransactionFactory) resolveClass(type).newInstance();
    factory.setProperties(props);
    return factory;
  }
  throw new BuilderException("Environment declaration requires a TransactionFactory.");
}
 
Example 9
Source File: XMLConfigBuilder.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private void typeAliasesElement(XNode parent) {
  if (parent != null) {
    for (XNode child : parent.getChildren()) {
      if ("package".equals(child.getName())) {
        //如果是package
        String typeAliasPackage = child.getStringAttribute("name");
        //(一)调用TypeAliasRegistry.registerAliases,去包下找所有类,然后注册别名(有@Alias注解则用,没有则取类的simpleName)
        configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
      } else {
        //如果是typeAlias
        String alias = child.getStringAttribute("alias");
        String type = child.getStringAttribute("type");
        try {
          Class<?> clazz = Resources.classForName(type);
          //根据Class名字来注册类型别名
          //(二)调用TypeAliasRegistry.registerAlias
          if (alias == null) {
            //alias可以省略
            typeAliasRegistry.registerAlias(clazz);
          } else {
            typeAliasRegistry.registerAlias(alias, clazz);
          }
        } catch (ClassNotFoundException e) {
          throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
        }
      }
    }
  }
}
 
Example 10
Source File: XMLScriptBuilder.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Override
public void handleNode(XNode nodeToHandle, List<SqlNode> targetContents) {
  List<SqlNode> contents = parseDynamicTags(nodeToHandle);
  MixedSqlNode mixedSqlNode = new MixedSqlNode(contents);
  String collection = nodeToHandle.getStringAttribute("collection");
  String item = nodeToHandle.getStringAttribute("item");
  String index = nodeToHandle.getStringAttribute("index");
  String open = nodeToHandle.getStringAttribute("open");
  String close = nodeToHandle.getStringAttribute("close");
  String separator = nodeToHandle.getStringAttribute("separator");
  ForEachSqlNode forEachSqlNode = new ForEachSqlNode(configuration, mixedSqlNode, collection, index, item, open, close, separator);
  targetContents.add(forEachSqlNode);
}
 
Example 11
Source File: XMLScriptBuilder.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Override
public void handleNode(XNode nodeToHandle, List<SqlNode> targetContents) {
  final String name = nodeToHandle.getStringAttribute("name");
  final String expression = nodeToHandle.getStringAttribute("value");
  final VarDeclSqlNode node = new VarDeclSqlNode(name, expression);
  targetContents.add(node);
}
 
Example 12
Source File: XMLStatementBuilder.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private void parseSelectKeyNodes(String parentId, List<XNode> list, Class<?> parameterTypeClass, LanguageDriver langDriver, String skRequiredDatabaseId) {
  for (XNode nodeToHandle : list) {
    String id = parentId + SelectKeyGenerator.SELECT_KEY_SUFFIX;
    String databaseId = nodeToHandle.getStringAttribute("databaseId");
    if (databaseIdMatchesCurrent(id, databaseId, skRequiredDatabaseId)) {
      parseSelectKeyNode(id, nodeToHandle, parameterTypeClass, langDriver, databaseId);
    }
  }
}
 
Example 13
Source File: MybatisMapperParser.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
private static String parseSql(String fileName,XNode node,Map<String, String> includeContents) {
	    StringBuilder sql = new StringBuilder();
	    NodeList children = node.getNode().getChildNodes();
	    for (int i = 0; i < children.getLength(); i++) {
	      XNode child = node.newXNode(children.item(i));
	      String data = null;
	      if("#text".equals(child.getName())){
	    	  data = child.getStringBody("");
	      }else if("include".equals(child.getName())){
	    	  String refId = child.getStringAttribute("refid");
	    	  data = child.toString();
	    	  if(includeContents.containsKey(refId)){	    		  
	    		  data = data.replaceAll("<\\s?include.*("+refId+").*>", includeContents.get(refId));
	    	  }else{
	    		  log.error(String.format(">>>>>Parse SQL from mapper[%s-%s] error,not found include key:%s", fileName,node.getStringAttribute("id"),refId));
	    	  }
	      }else{
	    	  data = child.toString();
//	    	  if(child.getStringBody().contains(">") || child.getStringBody().contains("<")){
//	    		  data = data.replace(child.getStringBody(), "<![CDATA["+child.getStringBody()+"]]");
//	    	  }
	      }
	      data = data.replaceAll("\\n+|\\t+", "");
	      if(StringUtils.isNotBlank(data)){	    	  
	    	  sql.append(data).append("\t").append("\n");
	      }
	    }
	    // return sql.toString().replaceAll("\\s{2,}", " ");
		return sql.toString();
	  }
 
Example 14
Source File: XMLConfigBuilder.java    From QuickProject with Apache License 2.0 5 votes vote down vote up
private TransactionFactory transactionManagerElement(XNode context) throws Exception {
  if (context != null) {
    String type = context.getStringAttribute("type");
    Properties props = context.getChildrenAsProperties();
    TransactionFactory factory = (TransactionFactory) resolveClass(type).newInstance();
    factory.setProperties(props);
    return factory;
  }
  throw new BuilderException("Environment declaration requires a TransactionFactory.");
}
 
Example 15
Source File: XMLMapperBuilder.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private void cacheRefElement(XNode context) {
  if (context != null) {
    //增加cache-ref
    configuration.addCacheRef(builderAssistant.getCurrentNamespace(), context.getStringAttribute("namespace"));
    CacheRefResolver cacheRefResolver = new CacheRefResolver(builderAssistant, context.getStringAttribute("namespace"));
    try {
      cacheRefResolver.resolveCacheRef();
    } catch (IncompleteElementException e) {
      configuration.addIncompleteCacheRef(cacheRefResolver);
    }
  }
}
 
Example 16
Source File: XMLConfigBuilder.java    From QuickProject with Apache License 2.0 5 votes vote down vote up
private void objectFactoryElement(XNode context) throws Exception {
  if (context != null) {
    String type = context.getStringAttribute("type");
    Properties properties = context.getChildrenAsProperties();
    ObjectFactory factory = (ObjectFactory) resolveClass(type).newInstance();
    factory.setProperties(properties);
    configuration.setObjectFactory(factory);
  }
}
 
Example 17
Source File: HierarchicalXMLConfigBuilder.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void reflectionFactoryElement(XNode context) throws Exception {
  if (context != null) {
    String type = context.getStringAttribute("type");
    ReflectorFactory factory = (ReflectorFactory) resolveClass(type).newInstance();
    configuration.setReflectorFactory(factory);
  }
}
 
Example 18
Source File: HierarchicalXMLConfigBuilder.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void objectFactoryElement(XNode context) throws Exception {
  if (context != null) {
    String type = context.getStringAttribute("type");
    Properties properties = context.getChildrenAsProperties();
    ObjectFactory factory = (ObjectFactory) resolveClass(type).newInstance();
    factory.setProperties(properties);
    configuration.setObjectFactory(factory);
  }
}
 
Example 19
Source File: HierarchicalXMLConfigBuilder.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void pluginElement(XNode parent) throws Exception {
    if (parent != null) {
        for (XNode child : parent.getChildren()) {
            String interceptor = child.getStringAttribute("interceptor");
            Properties properties = child.getChildrenAsProperties();
            Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
            interceptorInstance.setProperties(properties);
            configuration.addInterceptor(interceptorInstance);
        }
    }
}
 
Example 20
Source File: XMLMapperBuilder.java    From mybaties with Apache License 2.0 4 votes vote down vote up
private ResultMap resultMapElement(XNode resultMapNode, List<ResultMapping> additionalResultMappings) throws Exception {
    //错误上下文
//取得标示符   ("resultMap[userResultMap]")
//    <resultMap id="userResultMap" type="User">
//      <id property="id" column="user_id" />
//      <result property="username" column="username"/>
//      <result property="password" column="password"/>
//    </resultMap>
    ErrorContext.instance().activity("processing " + resultMapNode.getValueBasedIdentifier());
    String id = resultMapNode.getStringAttribute("id",
        resultMapNode.getValueBasedIdentifier());
    //一般拿type就可以了,后面3个难道是兼容老的代码?
    String type = resultMapNode.getStringAttribute("type",
        resultMapNode.getStringAttribute("ofType",
            resultMapNode.getStringAttribute("resultType",
                resultMapNode.getStringAttribute("javaType"))));
    //高级功能,还支持继承?
//  <resultMap id="carResult" type="Car" extends="vehicleResult">
//    <result property="doorCount" column="door_count" />
//  </resultMap>
    String extend = resultMapNode.getStringAttribute("extends");
    //autoMapping
    Boolean autoMapping = resultMapNode.getBooleanAttribute("autoMapping");
    Class<?> typeClass = resolveClass(type);
    Discriminator discriminator = null;
    List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();
    resultMappings.addAll(additionalResultMappings);
    List<XNode> resultChildren = resultMapNode.getChildren();
    for (XNode resultChild : resultChildren) {
      if ("constructor".equals(resultChild.getName())) {
        //解析result map的constructor
        processConstructorElement(resultChild, typeClass, resultMappings);
      } else if ("discriminator".equals(resultChild.getName())) {
        //解析result map的discriminator
        discriminator = processDiscriminatorElement(resultChild, typeClass, resultMappings);
      } else {
        List<ResultFlag> flags = new ArrayList<ResultFlag>();
        if ("id".equals(resultChild.getName())) {
          flags.add(ResultFlag.ID);
        }
        //调5.1.1 buildResultMappingFromContext,得到ResultMapping
        resultMappings.add(buildResultMappingFromContext(resultChild, typeClass, flags));
      }
    }
    //最后再调ResultMapResolver得到ResultMap
    ResultMapResolver resultMapResolver = new ResultMapResolver(builderAssistant, id, typeClass, extend, discriminator, resultMappings, autoMapping);
    try {
      return resultMapResolver.resolve();
    } catch (IncompleteElementException  e) {
      configuration.addIncompleteResultMap(resultMapResolver);
      throw e;
    }
  }