XMLMapperBuilder.java

  1. /*
  2.  *    Copyright 2009-2024 the original author or authors.
  3.  *
  4.  *    Licensed under the Apache License, Version 2.0 (the "License");
  5.  *    you may not use this file except in compliance with the License.
  6.  *    You may obtain a copy of the License at
  7.  *
  8.  *       https://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  *    Unless required by applicable law or agreed to in writing, software
  11.  *    distributed under the License is distributed on an "AS IS" BASIS,
  12.  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  *    See the License for the specific language governing permissions and
  14.  *    limitations under the License.
  15.  */
  16. package org.apache.ibatis.builder.xml;

  17. import java.io.InputStream;
  18. import java.io.Reader;
  19. import java.util.ArrayList;
  20. import java.util.Arrays;
  21. import java.util.Collections;
  22. import java.util.HashMap;
  23. import java.util.List;
  24. import java.util.Map;
  25. import java.util.Properties;

  26. import org.apache.ibatis.builder.BaseBuilder;
  27. import org.apache.ibatis.builder.BuilderException;
  28. import org.apache.ibatis.builder.CacheRefResolver;
  29. import org.apache.ibatis.builder.IncompleteElementException;
  30. import org.apache.ibatis.builder.MapperBuilderAssistant;
  31. import org.apache.ibatis.builder.ResultMapResolver;
  32. import org.apache.ibatis.cache.Cache;
  33. import org.apache.ibatis.executor.ErrorContext;
  34. import org.apache.ibatis.io.Resources;
  35. import org.apache.ibatis.mapping.Discriminator;
  36. import org.apache.ibatis.mapping.ParameterMapping;
  37. import org.apache.ibatis.mapping.ParameterMode;
  38. import org.apache.ibatis.mapping.ResultFlag;
  39. import org.apache.ibatis.mapping.ResultMap;
  40. import org.apache.ibatis.mapping.ResultMapping;
  41. import org.apache.ibatis.parsing.XNode;
  42. import org.apache.ibatis.parsing.XPathParser;
  43. import org.apache.ibatis.reflection.MetaClass;
  44. import org.apache.ibatis.session.Configuration;
  45. import org.apache.ibatis.type.JdbcType;
  46. import org.apache.ibatis.type.TypeHandler;

  47. /**
  48.  * @author Clinton Begin
  49.  * @author Kazuki Shimizu
  50.  */
  51. public class XMLMapperBuilder extends BaseBuilder {

  52.   private final XPathParser parser;
  53.   private final MapperBuilderAssistant builderAssistant;
  54.   private final Map<String, XNode> sqlFragments;
  55.   private final String resource;

  56.   @Deprecated
  57.   public XMLMapperBuilder(Reader reader, Configuration configuration, String resource, Map<String, XNode> sqlFragments,
  58.       String namespace) {
  59.     this(reader, configuration, resource, sqlFragments);
  60.     this.builderAssistant.setCurrentNamespace(namespace);
  61.   }

  62.   @Deprecated
  63.   public XMLMapperBuilder(Reader reader, Configuration configuration, String resource,
  64.       Map<String, XNode> sqlFragments) {
  65.     this(new XPathParser(reader, true, configuration.getVariables(), new XMLMapperEntityResolver()), configuration,
  66.         resource, sqlFragments);
  67.   }

  68.   public XMLMapperBuilder(InputStream inputStream, Configuration configuration, String resource,
  69.       Map<String, XNode> sqlFragments, String namespace) {
  70.     this(inputStream, configuration, resource, sqlFragments);
  71.     this.builderAssistant.setCurrentNamespace(namespace);
  72.   }

  73.   public XMLMapperBuilder(InputStream inputStream, Configuration configuration, String resource,
  74.       Map<String, XNode> sqlFragments) {
  75.     this(new XPathParser(inputStream, true, configuration.getVariables(), new XMLMapperEntityResolver()), configuration,
  76.         resource, sqlFragments);
  77.   }

  78.   private XMLMapperBuilder(XPathParser parser, Configuration configuration, String resource,
  79.       Map<String, XNode> sqlFragments) {
  80.     super(configuration);
  81.     this.builderAssistant = new MapperBuilderAssistant(configuration, resource);
  82.     this.parser = parser;
  83.     this.sqlFragments = sqlFragments;
  84.     this.resource = resource;
  85.   }

  86.   public void parse() {
  87.     if (!configuration.isResourceLoaded(resource)) {
  88.       configurationElement(parser.evalNode("/mapper"));
  89.       configuration.addLoadedResource(resource);
  90.       bindMapperForNamespace();
  91.     }
  92.     configuration.parsePendingResultMaps(false);
  93.     configuration.parsePendingCacheRefs(false);
  94.     configuration.parsePendingStatements(false);
  95.   }

  96.   public XNode getSqlFragment(String refid) {
  97.     return sqlFragments.get(refid);
  98.   }

  99.   private void configurationElement(XNode context) {
  100.     try {
  101.       String namespace = context.getStringAttribute("namespace");
  102.       if (namespace == null || namespace.isEmpty()) {
  103.         throw new BuilderException("Mapper's namespace cannot be empty");
  104.       }
  105.       builderAssistant.setCurrentNamespace(namespace);
  106.       cacheRefElement(context.evalNode("cache-ref"));
  107.       cacheElement(context.evalNode("cache"));
  108.       parameterMapElement(context.evalNodes("/mapper/parameterMap"));
  109.       resultMapElements(context.evalNodes("/mapper/resultMap"));
  110.       sqlElement(context.evalNodes("/mapper/sql"));
  111.       buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
  112.     } catch (Exception e) {
  113.       throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
  114.     }
  115.   }

  116.   private void buildStatementFromContext(List<XNode> list) {
  117.     if (configuration.getDatabaseId() != null) {
  118.       buildStatementFromContext(list, configuration.getDatabaseId());
  119.     }
  120.     buildStatementFromContext(list, null);
  121.   }

  122.   private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
  123.     for (XNode context : list) {
  124.       final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context,
  125.           requiredDatabaseId);
  126.       try {
  127.         statementParser.parseStatementNode();
  128.       } catch (IncompleteElementException e) {
  129.         configuration.addIncompleteStatement(statementParser);
  130.       }
  131.     }
  132.   }

  133.   private void cacheRefElement(XNode context) {
  134.     if (context != null) {
  135.       configuration.addCacheRef(builderAssistant.getCurrentNamespace(), context.getStringAttribute("namespace"));
  136.       CacheRefResolver cacheRefResolver = new CacheRefResolver(builderAssistant,
  137.           context.getStringAttribute("namespace"));
  138.       try {
  139.         cacheRefResolver.resolveCacheRef();
  140.       } catch (IncompleteElementException e) {
  141.         configuration.addIncompleteCacheRef(cacheRefResolver);
  142.       }
  143.     }
  144.   }

  145.   private void cacheElement(XNode context) {
  146.     if (context != null) {
  147.       String type = context.getStringAttribute("type", "PERPETUAL");
  148.       Class<? extends Cache> typeClass = typeAliasRegistry.resolveAlias(type);
  149.       String eviction = context.getStringAttribute("eviction", "LRU");
  150.       Class<? extends Cache> evictionClass = typeAliasRegistry.resolveAlias(eviction);
  151.       Long flushInterval = context.getLongAttribute("flushInterval");
  152.       Integer size = context.getIntAttribute("size");
  153.       boolean readWrite = !context.getBooleanAttribute("readOnly", false);
  154.       boolean blocking = context.getBooleanAttribute("blocking", false);
  155.       Properties props = context.getChildrenAsProperties();
  156.       builderAssistant.useNewCache(typeClass, evictionClass, flushInterval, size, readWrite, blocking, props);
  157.     }
  158.   }

  159.   private void parameterMapElement(List<XNode> list) {
  160.     for (XNode parameterMapNode : list) {
  161.       String id = parameterMapNode.getStringAttribute("id");
  162.       String type = parameterMapNode.getStringAttribute("type");
  163.       Class<?> parameterClass = resolveClass(type);
  164.       List<XNode> parameterNodes = parameterMapNode.evalNodes("parameter");
  165.       List<ParameterMapping> parameterMappings = new ArrayList<>();
  166.       for (XNode parameterNode : parameterNodes) {
  167.         String property = parameterNode.getStringAttribute("property");
  168.         String javaType = parameterNode.getStringAttribute("javaType");
  169.         String jdbcType = parameterNode.getStringAttribute("jdbcType");
  170.         String resultMap = parameterNode.getStringAttribute("resultMap");
  171.         String mode = parameterNode.getStringAttribute("mode");
  172.         String typeHandler = parameterNode.getStringAttribute("typeHandler");
  173.         Integer numericScale = parameterNode.getIntAttribute("numericScale");
  174.         ParameterMode modeEnum = resolveParameterMode(mode);
  175.         Class<?> javaTypeClass = resolveClass(javaType);
  176.         JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
  177.         Class<? extends TypeHandler<?>> typeHandlerClass = resolveClass(typeHandler);
  178.         ParameterMapping parameterMapping = builderAssistant.buildParameterMapping(parameterClass, property,
  179.             javaTypeClass, jdbcTypeEnum, resultMap, modeEnum, typeHandlerClass, numericScale);
  180.         parameterMappings.add(parameterMapping);
  181.       }
  182.       builderAssistant.addParameterMap(id, parameterClass, parameterMappings);
  183.     }
  184.   }

  185.   private void resultMapElements(List<XNode> list) {
  186.     for (XNode resultMapNode : list) {
  187.       try {
  188.         resultMapElement(resultMapNode);
  189.       } catch (IncompleteElementException e) {
  190.         // ignore, it will be retried
  191.       }
  192.     }
  193.   }

  194.   private ResultMap resultMapElement(XNode resultMapNode) {
  195.     return resultMapElement(resultMapNode, Collections.emptyList(), null);
  196.   }

  197.   private ResultMap resultMapElement(XNode resultMapNode, List<ResultMapping> additionalResultMappings,
  198.       Class<?> enclosingType) {
  199.     ErrorContext.instance().activity("processing " + resultMapNode.getValueBasedIdentifier());
  200.     String type = resultMapNode.getStringAttribute("type", resultMapNode.getStringAttribute("ofType",
  201.         resultMapNode.getStringAttribute("resultType", resultMapNode.getStringAttribute("javaType"))));
  202.     Class<?> typeClass = resolveClass(type);
  203.     if (typeClass == null) {
  204.       typeClass = inheritEnclosingType(resultMapNode, enclosingType);
  205.     }
  206.     Discriminator discriminator = null;
  207.     List<ResultMapping> resultMappings = new ArrayList<>(additionalResultMappings);
  208.     List<XNode> resultChildren = resultMapNode.getChildren();
  209.     for (XNode resultChild : resultChildren) {
  210.       if ("constructor".equals(resultChild.getName())) {
  211.         processConstructorElement(resultChild, typeClass, resultMappings);
  212.       } else if ("discriminator".equals(resultChild.getName())) {
  213.         discriminator = processDiscriminatorElement(resultChild, typeClass, resultMappings);
  214.       } else {
  215.         List<ResultFlag> flags = new ArrayList<>();
  216.         if ("id".equals(resultChild.getName())) {
  217.           flags.add(ResultFlag.ID);
  218.         }
  219.         resultMappings.add(buildResultMappingFromContext(resultChild, typeClass, flags));
  220.       }
  221.     }
  222.     String id = resultMapNode.getStringAttribute("id", resultMapNode::getValueBasedIdentifier);
  223.     String extend = resultMapNode.getStringAttribute("extends");
  224.     Boolean autoMapping = resultMapNode.getBooleanAttribute("autoMapping");
  225.     ResultMapResolver resultMapResolver = new ResultMapResolver(builderAssistant, id, typeClass, extend, discriminator,
  226.         resultMappings, autoMapping);
  227.     try {
  228.       return resultMapResolver.resolve();
  229.     } catch (IncompleteElementException e) {
  230.       configuration.addIncompleteResultMap(resultMapResolver);
  231.       throw e;
  232.     }
  233.   }

  234.   protected Class<?> inheritEnclosingType(XNode resultMapNode, Class<?> enclosingType) {
  235.     if ("association".equals(resultMapNode.getName()) && resultMapNode.getStringAttribute("resultMap") == null) {
  236.       String property = resultMapNode.getStringAttribute("property");
  237.       if (property != null && enclosingType != null) {
  238.         MetaClass metaResultType = MetaClass.forClass(enclosingType, configuration.getReflectorFactory());
  239.         return metaResultType.getSetterType(property);
  240.       }
  241.     } else if ("case".equals(resultMapNode.getName()) && resultMapNode.getStringAttribute("resultMap") == null) {
  242.       return enclosingType;
  243.     }
  244.     return null;
  245.   }

  246.   private void processConstructorElement(XNode resultChild, Class<?> resultType, List<ResultMapping> resultMappings) {
  247.     List<XNode> argChildren = resultChild.getChildren();
  248.     for (XNode argChild : argChildren) {
  249.       List<ResultFlag> flags = new ArrayList<>();
  250.       flags.add(ResultFlag.CONSTRUCTOR);
  251.       if ("idArg".equals(argChild.getName())) {
  252.         flags.add(ResultFlag.ID);
  253.       }
  254.       resultMappings.add(buildResultMappingFromContext(argChild, resultType, flags));
  255.     }
  256.   }

  257.   private Discriminator processDiscriminatorElement(XNode context, Class<?> resultType,
  258.       List<ResultMapping> resultMappings) {
  259.     String column = context.getStringAttribute("column");
  260.     String javaType = context.getStringAttribute("javaType");
  261.     String jdbcType = context.getStringAttribute("jdbcType");
  262.     String typeHandler = context.getStringAttribute("typeHandler");
  263.     Class<?> javaTypeClass = resolveClass(javaType);
  264.     Class<? extends TypeHandler<?>> typeHandlerClass = resolveClass(typeHandler);
  265.     JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
  266.     Map<String, String> discriminatorMap = new HashMap<>();
  267.     for (XNode caseChild : context.getChildren()) {
  268.       String value = caseChild.getStringAttribute("value");
  269.       String resultMap = caseChild.getStringAttribute("resultMap",
  270.           () -> processNestedResultMappings(caseChild, resultMappings, resultType));
  271.       discriminatorMap.put(value, resultMap);
  272.     }
  273.     return builderAssistant.buildDiscriminator(resultType, column, javaTypeClass, jdbcTypeEnum, typeHandlerClass,
  274.         discriminatorMap);
  275.   }

  276.   private void sqlElement(List<XNode> list) {
  277.     if (configuration.getDatabaseId() != null) {
  278.       sqlElement(list, configuration.getDatabaseId());
  279.     }
  280.     sqlElement(list, null);
  281.   }

  282.   private void sqlElement(List<XNode> list, String requiredDatabaseId) {
  283.     for (XNode context : list) {
  284.       String databaseId = context.getStringAttribute("databaseId");
  285.       String id = context.getStringAttribute("id");
  286.       id = builderAssistant.applyCurrentNamespace(id, false);
  287.       if (databaseIdMatchesCurrent(id, databaseId, requiredDatabaseId)) {
  288.         sqlFragments.put(id, context);
  289.       }
  290.     }
  291.   }

  292.   private boolean databaseIdMatchesCurrent(String id, String databaseId, String requiredDatabaseId) {
  293.     if (requiredDatabaseId != null) {
  294.       return requiredDatabaseId.equals(databaseId);
  295.     }
  296.     if (databaseId != null) {
  297.       return false;
  298.     }
  299.     if (!this.sqlFragments.containsKey(id)) {
  300.       return true;
  301.     }
  302.     // skip this fragment if there is a previous one with a not null databaseId
  303.     XNode context = this.sqlFragments.get(id);
  304.     return context.getStringAttribute("databaseId") == null;
  305.   }

  306.   private ResultMapping buildResultMappingFromContext(XNode context, Class<?> resultType, List<ResultFlag> flags) {
  307.     String property;
  308.     if (flags.contains(ResultFlag.CONSTRUCTOR)) {
  309.       property = context.getStringAttribute("name");
  310.     } else {
  311.       property = context.getStringAttribute("property");
  312.     }
  313.     String column = context.getStringAttribute("column");
  314.     String javaType = context.getStringAttribute("javaType");
  315.     String jdbcType = context.getStringAttribute("jdbcType");
  316.     String nestedSelect = context.getStringAttribute("select");
  317.     String nestedResultMap = context.getStringAttribute("resultMap",
  318.         () -> processNestedResultMappings(context, Collections.emptyList(), resultType));
  319.     String notNullColumn = context.getStringAttribute("notNullColumn");
  320.     String columnPrefix = context.getStringAttribute("columnPrefix");
  321.     String typeHandler = context.getStringAttribute("typeHandler");
  322.     String resultSet = context.getStringAttribute("resultSet");
  323.     String foreignColumn = context.getStringAttribute("foreignColumn");
  324.     boolean lazy = "lazy"
  325.         .equals(context.getStringAttribute("fetchType", configuration.isLazyLoadingEnabled() ? "lazy" : "eager"));
  326.     Class<?> javaTypeClass = resolveClass(javaType);
  327.     Class<? extends TypeHandler<?>> typeHandlerClass = resolveClass(typeHandler);
  328.     JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
  329.     return builderAssistant.buildResultMapping(resultType, property, column, javaTypeClass, jdbcTypeEnum, nestedSelect,
  330.         nestedResultMap, notNullColumn, columnPrefix, typeHandlerClass, flags, resultSet, foreignColumn, lazy);
  331.   }

  332.   private String processNestedResultMappings(XNode context, List<ResultMapping> resultMappings,
  333.       Class<?> enclosingType) {
  334.     if (Arrays.asList("association", "collection", "case").contains(context.getName())
  335.         && context.getStringAttribute("select") == null) {
  336.       validateCollection(context, enclosingType);
  337.       ResultMap resultMap = resultMapElement(context, resultMappings, enclosingType);
  338.       return resultMap.getId();
  339.     }
  340.     return null;
  341.   }

  342.   protected void validateCollection(XNode context, Class<?> enclosingType) {
  343.     if ("collection".equals(context.getName()) && context.getStringAttribute("resultMap") == null
  344.         && context.getStringAttribute("javaType") == null) {
  345.       MetaClass metaResultType = MetaClass.forClass(enclosingType, configuration.getReflectorFactory());
  346.       String property = context.getStringAttribute("property");
  347.       if (!metaResultType.hasSetter(property)) {
  348.         throw new BuilderException(
  349.             "Ambiguous collection type for property '" + property + "'. You must specify 'javaType' or 'resultMap'.");
  350.       }
  351.     }
  352.   }

  353.   private void bindMapperForNamespace() {
  354.     String namespace = builderAssistant.getCurrentNamespace();
  355.     if (namespace != null) {
  356.       Class<?> boundType = null;
  357.       try {
  358.         boundType = Resources.classForName(namespace);
  359.       } catch (ClassNotFoundException e) {
  360.         // ignore, bound type is not required
  361.       }
  362.       if (boundType != null && !configuration.hasMapper(boundType)) {
  363.         // Spring may not know the real resource name so we set a flag
  364.         // to prevent loading again this resource from the mapper interface
  365.         // look at MapperAnnotationBuilder#loadXmlResource
  366.         configuration.addLoadedResource("namespace:" + namespace);
  367.         configuration.addMapper(boundType);
  368.       }
  369.     }
  370.   }

  371. }