MapperBuilderAssistant.java

  1. /*
  2.  *    Copyright 2009-2023 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;

  17. import java.util.ArrayList;
  18. import java.util.Collections;
  19. import java.util.HashMap;
  20. import java.util.HashSet;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.Properties;
  24. import java.util.Set;
  25. import java.util.StringTokenizer;

  26. import org.apache.ibatis.cache.Cache;
  27. import org.apache.ibatis.cache.decorators.LruCache;
  28. import org.apache.ibatis.cache.impl.PerpetualCache;
  29. import org.apache.ibatis.executor.ErrorContext;
  30. import org.apache.ibatis.executor.keygen.KeyGenerator;
  31. import org.apache.ibatis.mapping.CacheBuilder;
  32. import org.apache.ibatis.mapping.Discriminator;
  33. import org.apache.ibatis.mapping.MappedStatement;
  34. import org.apache.ibatis.mapping.ParameterMap;
  35. import org.apache.ibatis.mapping.ParameterMapping;
  36. import org.apache.ibatis.mapping.ParameterMode;
  37. import org.apache.ibatis.mapping.ResultFlag;
  38. import org.apache.ibatis.mapping.ResultMap;
  39. import org.apache.ibatis.mapping.ResultMapping;
  40. import org.apache.ibatis.mapping.ResultSetType;
  41. import org.apache.ibatis.mapping.SqlCommandType;
  42. import org.apache.ibatis.mapping.SqlSource;
  43. import org.apache.ibatis.mapping.StatementType;
  44. import org.apache.ibatis.reflection.MetaClass;
  45. import org.apache.ibatis.scripting.LanguageDriver;
  46. import org.apache.ibatis.session.Configuration;
  47. import org.apache.ibatis.type.JdbcType;
  48. import org.apache.ibatis.type.TypeHandler;

  49. /**
  50.  * @author Clinton Begin
  51.  */
  52. public class MapperBuilderAssistant extends BaseBuilder {

  53.   private String currentNamespace;
  54.   private final String resource;
  55.   private Cache currentCache;
  56.   private boolean unresolvedCacheRef; // issue #676

  57.   public MapperBuilderAssistant(Configuration configuration, String resource) {
  58.     super(configuration);
  59.     ErrorContext.instance().resource(resource);
  60.     this.resource = resource;
  61.   }

  62.   public String getCurrentNamespace() {
  63.     return currentNamespace;
  64.   }

  65.   public void setCurrentNamespace(String currentNamespace) {
  66.     if (currentNamespace == null) {
  67.       throw new BuilderException("The mapper element requires a namespace attribute to be specified.");
  68.     }

  69.     if (this.currentNamespace != null && !this.currentNamespace.equals(currentNamespace)) {
  70.       throw new BuilderException(
  71.           "Wrong namespace. Expected '" + this.currentNamespace + "' but found '" + currentNamespace + "'.");
  72.     }

  73.     this.currentNamespace = currentNamespace;
  74.   }

  75.   public String applyCurrentNamespace(String base, boolean isReference) {
  76.     if (base == null) {
  77.       return null;
  78.     }
  79.     if (isReference) {
  80.       // is it qualified with any namespace yet?
  81.       if (base.contains(".")) {
  82.         return base;
  83.       }
  84.     } else {
  85.       // is it qualified with this namespace yet?
  86.       if (base.startsWith(currentNamespace + ".")) {
  87.         return base;
  88.       }
  89.       if (base.contains(".")) {
  90.         throw new BuilderException("Dots are not allowed in element names, please remove it from " + base);
  91.       }
  92.     }
  93.     return currentNamespace + "." + base;
  94.   }

  95.   public Cache useCacheRef(String namespace) {
  96.     if (namespace == null) {
  97.       throw new BuilderException("cache-ref element requires a namespace attribute.");
  98.     }
  99.     try {
  100.       unresolvedCacheRef = true;
  101.       Cache cache = configuration.getCache(namespace);
  102.       if (cache == null) {
  103.         throw new IncompleteElementException("No cache for namespace '" + namespace + "' could be found.");
  104.       }
  105.       currentCache = cache;
  106.       unresolvedCacheRef = false;
  107.       return cache;
  108.     } catch (IllegalArgumentException e) {
  109.       throw new IncompleteElementException("No cache for namespace '" + namespace + "' could be found.", e);
  110.     }
  111.   }

  112.   public Cache useNewCache(Class<? extends Cache> typeClass, Class<? extends Cache> evictionClass, Long flushInterval,
  113.       Integer size, boolean readWrite, boolean blocking, Properties props) {
  114.     Cache cache = new CacheBuilder(currentNamespace).implementation(valueOrDefault(typeClass, PerpetualCache.class))
  115.         .addDecorator(valueOrDefault(evictionClass, LruCache.class)).clearInterval(flushInterval).size(size)
  116.         .readWrite(readWrite).blocking(blocking).properties(props).build();
  117.     configuration.addCache(cache);
  118.     currentCache = cache;
  119.     return cache;
  120.   }

  121.   public ParameterMap addParameterMap(String id, Class<?> parameterClass, List<ParameterMapping> parameterMappings) {
  122.     id = applyCurrentNamespace(id, false);
  123.     ParameterMap parameterMap = new ParameterMap.Builder(configuration, id, parameterClass, parameterMappings).build();
  124.     configuration.addParameterMap(parameterMap);
  125.     return parameterMap;
  126.   }

  127.   public ParameterMapping buildParameterMapping(Class<?> parameterType, String property, Class<?> javaType,
  128.       JdbcType jdbcType, String resultMap, ParameterMode parameterMode, Class<? extends TypeHandler<?>> typeHandler,
  129.       Integer numericScale) {
  130.     resultMap = applyCurrentNamespace(resultMap, true);

  131.     // Class parameterType = parameterMapBuilder.type();
  132.     Class<?> javaTypeClass = resolveParameterJavaType(parameterType, property, javaType, jdbcType);
  133.     TypeHandler<?> typeHandlerInstance = resolveTypeHandler(javaTypeClass, typeHandler);

  134.     return new ParameterMapping.Builder(configuration, property, javaTypeClass).jdbcType(jdbcType)
  135.         .resultMapId(resultMap).mode(parameterMode).numericScale(numericScale).typeHandler(typeHandlerInstance).build();
  136.   }

  137.   public ResultMap addResultMap(String id, Class<?> type, String extend, Discriminator discriminator,
  138.       List<ResultMapping> resultMappings, Boolean autoMapping) {
  139.     id = applyCurrentNamespace(id, false);
  140.     extend = applyCurrentNamespace(extend, true);

  141.     if (extend != null) {
  142.       if (!configuration.hasResultMap(extend)) {
  143.         throw new IncompleteElementException("Could not find a parent resultmap with id '" + extend + "'");
  144.       }
  145.       ResultMap resultMap = configuration.getResultMap(extend);
  146.       List<ResultMapping> extendedResultMappings = new ArrayList<>(resultMap.getResultMappings());
  147.       extendedResultMappings.removeAll(resultMappings);
  148.       // Remove parent constructor if this resultMap declares a constructor.
  149.       boolean declaresConstructor = false;
  150.       for (ResultMapping resultMapping : resultMappings) {
  151.         if (resultMapping.getFlags().contains(ResultFlag.CONSTRUCTOR)) {
  152.           declaresConstructor = true;
  153.           break;
  154.         }
  155.       }
  156.       if (declaresConstructor) {
  157.         extendedResultMappings.removeIf(resultMapping -> resultMapping.getFlags().contains(ResultFlag.CONSTRUCTOR));
  158.       }
  159.       resultMappings.addAll(extendedResultMappings);
  160.     }
  161.     ResultMap resultMap = new ResultMap.Builder(configuration, id, type, resultMappings, autoMapping)
  162.         .discriminator(discriminator).build();
  163.     configuration.addResultMap(resultMap);
  164.     return resultMap;
  165.   }

  166.   public Discriminator buildDiscriminator(Class<?> resultType, String column, Class<?> javaType, JdbcType jdbcType,
  167.       Class<? extends TypeHandler<?>> typeHandler, Map<String, String> discriminatorMap) {
  168.     ResultMapping resultMapping = buildResultMapping(resultType, null, column, javaType, jdbcType, null, null, null,
  169.         null, typeHandler, new ArrayList<>(), null, null, false);
  170.     Map<String, String> namespaceDiscriminatorMap = new HashMap<>();
  171.     for (Map.Entry<String, String> e : discriminatorMap.entrySet()) {
  172.       String resultMap = e.getValue();
  173.       resultMap = applyCurrentNamespace(resultMap, true);
  174.       namespaceDiscriminatorMap.put(e.getKey(), resultMap);
  175.     }
  176.     return new Discriminator.Builder(configuration, resultMapping, namespaceDiscriminatorMap).build();
  177.   }

  178.   public MappedStatement addMappedStatement(String id, SqlSource sqlSource, StatementType statementType,
  179.       SqlCommandType sqlCommandType, Integer fetchSize, Integer timeout, String parameterMap, Class<?> parameterType,
  180.       String resultMap, Class<?> resultType, ResultSetType resultSetType, boolean flushCache, boolean useCache,
  181.       boolean resultOrdered, KeyGenerator keyGenerator, String keyProperty, String keyColumn, String databaseId,
  182.       LanguageDriver lang, String resultSets, boolean dirtySelect) {

  183.     if (unresolvedCacheRef) {
  184.       throw new IncompleteElementException("Cache-ref not yet resolved");
  185.     }

  186.     id = applyCurrentNamespace(id, false);

  187.     MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType)
  188.         .resource(resource).fetchSize(fetchSize).timeout(timeout).statementType(statementType)
  189.         .keyGenerator(keyGenerator).keyProperty(keyProperty).keyColumn(keyColumn).databaseId(databaseId).lang(lang)
  190.         .resultOrdered(resultOrdered).resultSets(resultSets)
  191.         .resultMaps(getStatementResultMaps(resultMap, resultType, id)).resultSetType(resultSetType)
  192.         .flushCacheRequired(flushCache).useCache(useCache).cache(currentCache).dirtySelect(dirtySelect);

  193.     ParameterMap statementParameterMap = getStatementParameterMap(parameterMap, parameterType, id);
  194.     if (statementParameterMap != null) {
  195.       statementBuilder.parameterMap(statementParameterMap);
  196.     }

  197.     MappedStatement statement = statementBuilder.build();
  198.     configuration.addMappedStatement(statement);
  199.     return statement;
  200.   }

  201.   /**
  202.    * Backward compatibility signature 'addMappedStatement'.
  203.    *
  204.    * @param id
  205.    *          the id
  206.    * @param sqlSource
  207.    *          the sql source
  208.    * @param statementType
  209.    *          the statement type
  210.    * @param sqlCommandType
  211.    *          the sql command type
  212.    * @param fetchSize
  213.    *          the fetch size
  214.    * @param timeout
  215.    *          the timeout
  216.    * @param parameterMap
  217.    *          the parameter map
  218.    * @param parameterType
  219.    *          the parameter type
  220.    * @param resultMap
  221.    *          the result map
  222.    * @param resultType
  223.    *          the result type
  224.    * @param resultSetType
  225.    *          the result set type
  226.    * @param flushCache
  227.    *          the flush cache
  228.    * @param useCache
  229.    *          the use cache
  230.    * @param resultOrdered
  231.    *          the result ordered
  232.    * @param keyGenerator
  233.    *          the key generator
  234.    * @param keyProperty
  235.    *          the key property
  236.    * @param keyColumn
  237.    *          the key column
  238.    * @param databaseId
  239.    *          the database id
  240.    * @param lang
  241.    *          the lang
  242.    *
  243.    * @return the mapped statement
  244.    */
  245.   public MappedStatement addMappedStatement(String id, SqlSource sqlSource, StatementType statementType,
  246.       SqlCommandType sqlCommandType, Integer fetchSize, Integer timeout, String parameterMap, Class<?> parameterType,
  247.       String resultMap, Class<?> resultType, ResultSetType resultSetType, boolean flushCache, boolean useCache,
  248.       boolean resultOrdered, KeyGenerator keyGenerator, String keyProperty, String keyColumn, String databaseId,
  249.       LanguageDriver lang, String resultSets) {
  250.     return addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, parameterMap,
  251.         parameterType, resultMap, resultType, resultSetType, flushCache, useCache, resultOrdered, keyGenerator,
  252.         keyProperty, keyColumn, databaseId, lang, null, false);
  253.   }

  254.   public MappedStatement addMappedStatement(String id, SqlSource sqlSource, StatementType statementType,
  255.       SqlCommandType sqlCommandType, Integer fetchSize, Integer timeout, String parameterMap, Class<?> parameterType,
  256.       String resultMap, Class<?> resultType, ResultSetType resultSetType, boolean flushCache, boolean useCache,
  257.       boolean resultOrdered, KeyGenerator keyGenerator, String keyProperty, String keyColumn, String databaseId,
  258.       LanguageDriver lang) {
  259.     return addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, parameterMap,
  260.         parameterType, resultMap, resultType, resultSetType, flushCache, useCache, resultOrdered, keyGenerator,
  261.         keyProperty, keyColumn, databaseId, lang, null);
  262.   }

  263.   private <T> T valueOrDefault(T value, T defaultValue) {
  264.     return value == null ? defaultValue : value;
  265.   }

  266.   private ParameterMap getStatementParameterMap(String parameterMapName, Class<?> parameterTypeClass,
  267.       String statementId) {
  268.     parameterMapName = applyCurrentNamespace(parameterMapName, true);
  269.     ParameterMap parameterMap = null;
  270.     if (parameterMapName != null) {
  271.       try {
  272.         parameterMap = configuration.getParameterMap(parameterMapName);
  273.       } catch (IllegalArgumentException e) {
  274.         throw new IncompleteElementException("Could not find parameter map " + parameterMapName, e);
  275.       }
  276.     } else if (parameterTypeClass != null) {
  277.       List<ParameterMapping> parameterMappings = new ArrayList<>();
  278.       parameterMap = new ParameterMap.Builder(configuration, statementId + "-Inline", parameterTypeClass,
  279.           parameterMappings).build();
  280.     }
  281.     return parameterMap;
  282.   }

  283.   private List<ResultMap> getStatementResultMaps(String resultMap, Class<?> resultType, String statementId) {
  284.     resultMap = applyCurrentNamespace(resultMap, true);

  285.     List<ResultMap> resultMaps = new ArrayList<>();
  286.     if (resultMap != null) {
  287.       String[] resultMapNames = resultMap.split(",");
  288.       for (String resultMapName : resultMapNames) {
  289.         try {
  290.           resultMaps.add(configuration.getResultMap(resultMapName.trim()));
  291.         } catch (IllegalArgumentException e) {
  292.           throw new IncompleteElementException(
  293.               "Could not find result map '" + resultMapName + "' referenced from '" + statementId + "'", e);
  294.         }
  295.       }
  296.     } else if (resultType != null) {
  297.       ResultMap inlineResultMap = new ResultMap.Builder(configuration, statementId + "-Inline", resultType,
  298.           new ArrayList<>(), null).build();
  299.       resultMaps.add(inlineResultMap);
  300.     }
  301.     return resultMaps;
  302.   }

  303.   public ResultMapping buildResultMapping(Class<?> resultType, String property, String column, Class<?> javaType,
  304.       JdbcType jdbcType, String nestedSelect, String nestedResultMap, String notNullColumn, String columnPrefix,
  305.       Class<? extends TypeHandler<?>> typeHandler, List<ResultFlag> flags, String resultSet, String foreignColumn,
  306.       boolean lazy) {
  307.     Class<?> javaTypeClass = resolveResultJavaType(resultType, property, javaType);
  308.     TypeHandler<?> typeHandlerInstance = resolveTypeHandler(javaTypeClass, typeHandler);
  309.     List<ResultMapping> composites;
  310.     if ((nestedSelect == null || nestedSelect.isEmpty()) && (foreignColumn == null || foreignColumn.isEmpty())) {
  311.       composites = Collections.emptyList();
  312.     } else {
  313.       composites = parseCompositeColumnName(column);
  314.     }
  315.     return new ResultMapping.Builder(configuration, property, column, javaTypeClass).jdbcType(jdbcType)
  316.         .nestedQueryId(applyCurrentNamespace(nestedSelect, true))
  317.         .nestedResultMapId(applyCurrentNamespace(nestedResultMap, true)).resultSet(resultSet)
  318.         .typeHandler(typeHandlerInstance).flags(flags == null ? new ArrayList<>() : flags).composites(composites)
  319.         .notNullColumns(parseMultipleColumnNames(notNullColumn)).columnPrefix(columnPrefix).foreignColumn(foreignColumn)
  320.         .lazy(lazy).build();
  321.   }

  322.   /**
  323.    * Backward compatibility signature 'buildResultMapping'.
  324.    *
  325.    * @param resultType
  326.    *          the result type
  327.    * @param property
  328.    *          the property
  329.    * @param column
  330.    *          the column
  331.    * @param javaType
  332.    *          the java type
  333.    * @param jdbcType
  334.    *          the jdbc type
  335.    * @param nestedSelect
  336.    *          the nested select
  337.    * @param nestedResultMap
  338.    *          the nested result map
  339.    * @param notNullColumn
  340.    *          the not null column
  341.    * @param columnPrefix
  342.    *          the column prefix
  343.    * @param typeHandler
  344.    *          the type handler
  345.    * @param flags
  346.    *          the flags
  347.    *
  348.    * @return the result mapping
  349.    */
  350.   public ResultMapping buildResultMapping(Class<?> resultType, String property, String column, Class<?> javaType,
  351.       JdbcType jdbcType, String nestedSelect, String nestedResultMap, String notNullColumn, String columnPrefix,
  352.       Class<? extends TypeHandler<?>> typeHandler, List<ResultFlag> flags) {
  353.     return buildResultMapping(resultType, property, column, javaType, jdbcType, nestedSelect, nestedResultMap,
  354.         notNullColumn, columnPrefix, typeHandler, flags, null, null, configuration.isLazyLoadingEnabled());
  355.   }

  356.   /**
  357.    * Gets the language driver.
  358.    *
  359.    * @param langClass
  360.    *          the lang class
  361.    *
  362.    * @return the language driver
  363.    *
  364.    * @deprecated Use {@link Configuration#getLanguageDriver(Class)}
  365.    */
  366.   @Deprecated
  367.   public LanguageDriver getLanguageDriver(Class<? extends LanguageDriver> langClass) {
  368.     return configuration.getLanguageDriver(langClass);
  369.   }

  370.   private Set<String> parseMultipleColumnNames(String columnName) {
  371.     Set<String> columns = new HashSet<>();
  372.     if (columnName != null) {
  373.       if (columnName.indexOf(',') > -1) {
  374.         StringTokenizer parser = new StringTokenizer(columnName, "{}, ", false);
  375.         while (parser.hasMoreTokens()) {
  376.           String column = parser.nextToken();
  377.           columns.add(column);
  378.         }
  379.       } else {
  380.         columns.add(columnName);
  381.       }
  382.     }
  383.     return columns;
  384.   }

  385.   private List<ResultMapping> parseCompositeColumnName(String columnName) {
  386.     List<ResultMapping> composites = new ArrayList<>();
  387.     if (columnName != null && (columnName.indexOf('=') > -1 || columnName.indexOf(',') > -1)) {
  388.       StringTokenizer parser = new StringTokenizer(columnName, "{}=, ", false);
  389.       while (parser.hasMoreTokens()) {
  390.         String property = parser.nextToken();
  391.         String column = parser.nextToken();
  392.         ResultMapping complexResultMapping = new ResultMapping.Builder(configuration, property, column,
  393.             configuration.getTypeHandlerRegistry().getUnknownTypeHandler()).build();
  394.         composites.add(complexResultMapping);
  395.       }
  396.     }
  397.     return composites;
  398.   }

  399.   private Class<?> resolveResultJavaType(Class<?> resultType, String property, Class<?> javaType) {
  400.     if (javaType == null && property != null) {
  401.       try {
  402.         MetaClass metaResultType = MetaClass.forClass(resultType, configuration.getReflectorFactory());
  403.         javaType = metaResultType.getSetterType(property);
  404.       } catch (Exception e) {
  405.         // ignore, following null check statement will deal with the situation
  406.       }
  407.     }
  408.     if (javaType == null) {
  409.       javaType = Object.class;
  410.     }
  411.     return javaType;
  412.   }

  413.   private Class<?> resolveParameterJavaType(Class<?> resultType, String property, Class<?> javaType,
  414.       JdbcType jdbcType) {
  415.     if (javaType == null) {
  416.       if (JdbcType.CURSOR.equals(jdbcType)) {
  417.         javaType = java.sql.ResultSet.class;
  418.       } else if (Map.class.isAssignableFrom(resultType)) {
  419.         javaType = Object.class;
  420.       } else {
  421.         MetaClass metaResultType = MetaClass.forClass(resultType, configuration.getReflectorFactory());
  422.         javaType = metaResultType.getGetterType(property);
  423.       }
  424.     }
  425.     if (javaType == null) {
  426.       javaType = Object.class;
  427.     }
  428.     return javaType;
  429.   }

  430. }