View Javadoc
1   /*
2    *    Copyright 2009-2026 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  
18  import java.lang.reflect.Type;
19  import java.sql.ResultSet;
20  import java.util.ArrayList;
21  import java.util.HashMap;
22  import java.util.HashSet;
23  import java.util.List;
24  import java.util.Map;
25  import java.util.Map.Entry;
26  import java.util.Properties;
27  import java.util.Set;
28  import java.util.StringTokenizer;
29  
30  import org.apache.ibatis.cache.Cache;
31  import org.apache.ibatis.cache.decorators.LruCache;
32  import org.apache.ibatis.cache.impl.PerpetualCache;
33  import org.apache.ibatis.executor.ErrorContext;
34  import org.apache.ibatis.executor.keygen.KeyGenerator;
35  import org.apache.ibatis.mapping.CacheBuilder;
36  import org.apache.ibatis.mapping.Discriminator;
37  import org.apache.ibatis.mapping.MappedStatement;
38  import org.apache.ibatis.mapping.ParameterMap;
39  import org.apache.ibatis.mapping.ParameterMapping;
40  import org.apache.ibatis.mapping.ParameterMode;
41  import org.apache.ibatis.mapping.ResultFlag;
42  import org.apache.ibatis.mapping.ResultMap;
43  import org.apache.ibatis.mapping.ResultMapping;
44  import org.apache.ibatis.mapping.ResultSetType;
45  import org.apache.ibatis.mapping.SqlCommandType;
46  import org.apache.ibatis.mapping.SqlSource;
47  import org.apache.ibatis.mapping.StatementType;
48  import org.apache.ibatis.reflection.MetaClass;
49  import org.apache.ibatis.reflection.ParamNameResolver;
50  import org.apache.ibatis.scripting.LanguageDriver;
51  import org.apache.ibatis.session.Configuration;
52  import org.apache.ibatis.type.JdbcType;
53  import org.apache.ibatis.type.TypeHandler;
54  
55  /**
56   * @author Clinton Begin
57   */
58  public class MapperBuilderAssistant extends BaseBuilder {
59  
60    private String currentNamespace;
61    private final String resource;
62    private Cache currentCache;
63    private boolean unresolvedCacheRef; // issue #676
64  
65    public MapperBuilderAssistant(Configuration configuration, String resource) {
66      super(configuration);
67      ErrorContext.instance().resource(resource);
68      this.resource = resource;
69    }
70  
71    public String getCurrentNamespace() {
72      return currentNamespace;
73    }
74  
75    public void setCurrentNamespace(String currentNamespace) {
76      if (currentNamespace == null) {
77        throw new BuilderException("The mapper element requires a namespace attribute to be specified.");
78      }
79  
80      if (this.currentNamespace != null && !this.currentNamespace.equals(currentNamespace)) {
81        throw new BuilderException(
82            "Wrong namespace. Expected '" + this.currentNamespace + "' but found '" + currentNamespace + "'.");
83      }
84  
85      this.currentNamespace = currentNamespace;
86    }
87  
88    public String applyCurrentNamespace(String base, boolean isReference) {
89      if (base == null) {
90        return null;
91      }
92      if (isReference) {
93        // is it qualified with any namespace yet?
94        if (base.contains(".")) {
95          return base;
96        }
97      } else {
98        // is it qualified with this namespace yet?
99        if (base.startsWith(currentNamespace + ".")) {
100         return base;
101       }
102       if (base.contains(".")) {
103         throw new BuilderException("Dots are not allowed in element names, please remove it from " + base);
104       }
105     }
106     return currentNamespace + "." + base;
107   }
108 
109   public Cache useCacheRef(String namespace) {
110     if (namespace == null) {
111       throw new BuilderException("cache-ref element requires a namespace attribute.");
112     }
113     try {
114       unresolvedCacheRef = true;
115       Cache cache = configuration.getCache(namespace);
116       if (cache == null) {
117         throw new IncompleteElementException("No cache for namespace '" + namespace + "' could be found.");
118       }
119       currentCache = cache;
120       unresolvedCacheRef = false;
121       return cache;
122     } catch (IllegalArgumentException e) {
123       throw new IncompleteElementException("No cache for namespace '" + namespace + "' could be found.", e);
124     }
125   }
126 
127   public Cache useNewCache(Class<? extends Cache> typeClass, Class<? extends Cache> evictionClass, Long flushInterval,
128       Integer size, boolean readWrite, boolean blocking, Properties props) {
129     Cache cache = new CacheBuilder(currentNamespace).implementation(valueOrDefault(typeClass, PerpetualCache.class))
130         .addDecorator(valueOrDefault(evictionClass, LruCache.class)).clearInterval(flushInterval).size(size)
131         .readWrite(readWrite).blocking(blocking).properties(props).build();
132     configuration.addCache(cache);
133     currentCache = cache;
134     return cache;
135   }
136 
137   public ParameterMap addParameterMap(String id, Class<?> parameterClass, List<ParameterMapping> parameterMappings) {
138     id = applyCurrentNamespace(id, false);
139     ParameterMap parameterMap = new ParameterMap.Builder(configuration, id, parameterClass, parameterMappings).build();
140     configuration.addParameterMap(parameterMap);
141     return parameterMap;
142   }
143 
144   public ParameterMapping buildParameterMapping(Class<?> parameterType, String property, Class<?> javaType,
145       JdbcType jdbcType, String resultMap, ParameterMode parameterMode, Class<? extends TypeHandler<?>> typeHandler,
146       Integer numericScale) {
147     resultMap = applyCurrentNamespace(resultMap, true);
148 
149     // Class parameterType = parameterMapBuilder.type();
150     Class<?> javaTypeClass = resolveParameterJavaType(parameterType, property, javaType, jdbcType);
151     TypeHandler<?> typeHandlerInstance = resolveTypeHandler(javaTypeClass, jdbcType, typeHandler);
152 
153     return new ParameterMapping.Builder(configuration, property, javaTypeClass).jdbcType(jdbcType)
154         .resultMapId(resultMap).mode(parameterMode).numericScale(numericScale).typeHandler(typeHandlerInstance).build();
155   }
156 
157   public ResultMap addResultMap(String id, Class<?> type, String extend, Discriminator discriminator,
158       List<ResultMapping> resultMappings, Boolean autoMapping) {
159     id = applyCurrentNamespace(id, false);
160     extend = applyCurrentNamespace(extend, true);
161 
162     if (extend != null) {
163       if (!configuration.hasResultMap(extend)) {
164         throw new IncompleteElementException("Could not find a parent resultMap with id '" + extend + "'");
165       }
166       ResultMap resultMap = configuration.getResultMap(extend);
167       List<ResultMapping> extendedResultMappings = new ArrayList<>(resultMap.getResultMappings());
168       extendedResultMappings.removeAll(resultMappings);
169       // Remove parent constructor if this resultMap declares a constructor.
170       boolean declaresConstructor = false;
171       for (ResultMapping resultMapping : resultMappings) {
172         if (resultMapping.getFlags().contains(ResultFlag.CONSTRUCTOR)) {
173           declaresConstructor = true;
174           break;
175         }
176       }
177       if (declaresConstructor) {
178         extendedResultMappings.removeIf(resultMapping -> resultMapping.getFlags().contains(ResultFlag.CONSTRUCTOR));
179       }
180       resultMappings.addAll(extendedResultMappings);
181     }
182     ResultMap resultMap = new ResultMap.Builder(configuration, id, type, resultMappings, autoMapping)
183         .discriminator(discriminator).build();
184     configuration.addResultMap(resultMap);
185     return resultMap;
186   }
187 
188   public Discriminator buildDiscriminator(Class<?> resultType, String column, Class<?> javaType, JdbcType jdbcType,
189       Class<? extends TypeHandler<?>> typeHandler, Map<String, String> discriminatorMap) {
190     ResultMapping resultMapping = buildResultMapping(resultType, null, column, javaType, jdbcType, null, null, null,
191         null, typeHandler, new ArrayList<>(), null, null, false);
192     Map<String, String> namespaceDiscriminatorMap = new HashMap<>();
193     for (Map.Entry<String, String> e : discriminatorMap.entrySet()) {
194       String resultMap = e.getValue();
195       resultMap = applyCurrentNamespace(resultMap, true);
196       namespaceDiscriminatorMap.put(e.getKey(), resultMap);
197     }
198     return new Discriminator.Builder(configuration, resultMapping, namespaceDiscriminatorMap).build();
199   }
200 
201   public MappedStatement addMappedStatement(String id, SqlSource sqlSource, StatementType statementType,
202       SqlCommandType sqlCommandType, Integer fetchSize, Integer timeout, String parameterMap, Class<?> parameterType,
203       String resultMap, Class<?> resultType, ResultSetType resultSetType, boolean flushCache, boolean useCache,
204       boolean resultOrdered, KeyGenerator keyGenerator, String keyProperty, String keyColumn, String databaseId,
205       LanguageDriver lang, String resultSets, boolean dirtySelect, ParamNameResolver paramNameResolver) {
206 
207     if (unresolvedCacheRef) {
208       throw new IncompleteElementException("Cache-ref not yet resolved");
209     }
210 
211     id = applyCurrentNamespace(id, false);
212 
213     MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType)
214         .resource(resource).fetchSize(fetchSize).timeout(timeout).statementType(statementType)
215         .keyGenerator(keyGenerator).keyProperty(keyProperty).keyColumn(keyColumn).databaseId(databaseId).lang(lang)
216         .resultOrdered(resultOrdered).resultSets(resultSets)
217         .resultMaps(getStatementResultMaps(resultMap, resultType, id)).resultSetType(resultSetType)
218         .flushCacheRequired(flushCache).useCache(useCache).cache(currentCache).dirtySelect(dirtySelect)
219         .paramNameResolver(paramNameResolver);
220 
221     ParameterMap statementParameterMap = getStatementParameterMap(parameterMap, parameterType, id);
222     if (statementParameterMap != null) {
223       statementBuilder.parameterMap(statementParameterMap);
224     }
225 
226     MappedStatement statement = statementBuilder.build();
227     configuration.addMappedStatement(statement);
228     return statement;
229   }
230 
231   /**
232    * Backward compatibility signature 'addMappedStatement'.
233    *
234    * @param id
235    *          the id
236    * @param sqlSource
237    *          the sql source
238    * @param statementType
239    *          the statement type
240    * @param sqlCommandType
241    *          the sql command type
242    * @param fetchSize
243    *          the fetch size
244    * @param timeout
245    *          the timeout
246    * @param parameterMap
247    *          the parameter map
248    * @param parameterType
249    *          the parameter type
250    * @param resultMap
251    *          the result map
252    * @param resultType
253    *          the result type
254    * @param resultSetType
255    *          the result set type
256    * @param flushCache
257    *          the flush cache
258    * @param useCache
259    *          the use cache
260    * @param resultOrdered
261    *          the result ordered
262    * @param keyGenerator
263    *          the key generator
264    * @param keyProperty
265    *          the key property
266    * @param keyColumn
267    *          the key column
268    * @param databaseId
269    *          the database id
270    * @param lang
271    *          the lang
272    *
273    * @return the mapped statement
274    */
275   public MappedStatement addMappedStatement(String id, SqlSource sqlSource, StatementType statementType,
276       SqlCommandType sqlCommandType, Integer fetchSize, Integer timeout, String parameterMap, Class<?> parameterType,
277       String resultMap, Class<?> resultType, ResultSetType resultSetType, boolean flushCache, boolean useCache,
278       boolean resultOrdered, KeyGenerator keyGenerator, String keyProperty, String keyColumn, String databaseId,
279       LanguageDriver lang, String resultSets) {
280     return addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, parameterMap,
281         parameterType, resultMap, resultType, resultSetType, flushCache, useCache, resultOrdered, keyGenerator,
282         keyProperty, keyColumn, databaseId, lang, null, false, null);
283   }
284 
285   public MappedStatement addMappedStatement(String id, SqlSource sqlSource, StatementType statementType,
286       SqlCommandType sqlCommandType, Integer fetchSize, Integer timeout, String parameterMap, Class<?> parameterType,
287       String resultMap, Class<?> resultType, ResultSetType resultSetType, boolean flushCache, boolean useCache,
288       boolean resultOrdered, KeyGenerator keyGenerator, String keyProperty, String keyColumn, String databaseId,
289       LanguageDriver lang) {
290     return addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, parameterMap,
291         parameterType, resultMap, resultType, resultSetType, flushCache, useCache, resultOrdered, keyGenerator,
292         keyProperty, keyColumn, databaseId, lang, null);
293   }
294 
295   private <T> T valueOrDefault(T value, T defaultValue) {
296     return value == null ? defaultValue : value;
297   }
298 
299   private ParameterMap getStatementParameterMap(String parameterMapName, Class<?> parameterTypeClass,
300       String statementId) {
301     parameterMapName = applyCurrentNamespace(parameterMapName, true);
302     ParameterMap parameterMap = null;
303     if (parameterMapName != null) {
304       try {
305         parameterMap = configuration.getParameterMap(parameterMapName);
306       } catch (IllegalArgumentException e) {
307         throw new IncompleteElementException("Could not find parameter map " + parameterMapName, e);
308       }
309     } else if (parameterTypeClass != null) {
310       parameterMap = ParameterMap.buildEmpty(statementId + "-Inline", parameterTypeClass);
311     }
312     return parameterMap;
313   }
314 
315   private List<ResultMap> getStatementResultMaps(String resultMap, Class<?> resultType, String statementId) {
316     resultMap = applyCurrentNamespace(resultMap, true);
317 
318     List<ResultMap> resultMaps = new ArrayList<>();
319     if (resultMap != null) {
320       String[] resultMapNames = resultMap.split(",");
321       for (String resultMapName : resultMapNames) {
322         try {
323           resultMaps.add(configuration.getResultMap(resultMapName.trim()));
324         } catch (IllegalArgumentException e) {
325           throw new IncompleteElementException(
326               "Could not find result map '" + resultMapName + "' referenced from '" + statementId + "'", e);
327         }
328       }
329     } else if (resultType != null) {
330       resultMaps.add(ResultMap.buildEmpty(configuration, statementId + "-Inline", resultType));
331     }
332     return resultMaps;
333   }
334 
335   public ResultMapping buildResultMapping(Class<?> resultType, String property, String column, Class<?> javaType,
336       JdbcType jdbcType, String nestedSelect, String nestedResultMap, String notNullColumn, String columnPrefix,
337       Class<? extends TypeHandler<?>> typeHandler, List<ResultFlag> flags, String resultSet, String foreignColumn,
338       boolean lazy) {
339     Entry<Type, Class<?>> setterType = resolveSetterType(resultType, property, javaType);
340     TypeHandler<?> typeHandlerInstance = resolveTypeHandler(setterType.getKey(), jdbcType, typeHandler);
341     List<ResultMapping> composites;
342     if ((nestedSelect == null || nestedSelect.isEmpty()) && (foreignColumn == null || foreignColumn.isEmpty())) {
343       composites = List.of();
344     } else {
345       composites = parseCompositeColumnName(column);
346     }
347     return new ResultMapping.Builder(configuration, property, column, setterType.getValue()).jdbcType(jdbcType)
348         .nestedQueryId(applyCurrentNamespace(nestedSelect, true))
349         .nestedResultMapId(applyCurrentNamespace(nestedResultMap, true)).resultSet(resultSet)
350         .typeHandler(typeHandlerInstance).flags(flags == null ? new ArrayList<>() : flags).composites(composites)
351         .notNullColumns(parseMultipleColumnNames(notNullColumn)).columnPrefix(columnPrefix).foreignColumn(foreignColumn)
352         .lazy(lazy).build();
353   }
354 
355   /**
356    * Backward compatibility signature 'buildResultMapping'.
357    *
358    * @param resultType
359    *          the result type
360    * @param property
361    *          the property
362    * @param column
363    *          the column
364    * @param javaType
365    *          the java type
366    * @param jdbcType
367    *          the jdbc type
368    * @param nestedSelect
369    *          the nested select
370    * @param nestedResultMap
371    *          the nested result map
372    * @param notNullColumn
373    *          the not null column
374    * @param columnPrefix
375    *          the column prefix
376    * @param typeHandler
377    *          the type handler
378    * @param flags
379    *          the flags
380    *
381    * @return the result mapping
382    */
383   public ResultMapping buildResultMapping(Class<?> resultType, String property, String column, Class<?> javaType,
384       JdbcType jdbcType, String nestedSelect, String nestedResultMap, String notNullColumn, String columnPrefix,
385       Class<? extends TypeHandler<?>> typeHandler, List<ResultFlag> flags) {
386     return buildResultMapping(resultType, property, column, javaType, jdbcType, nestedSelect, nestedResultMap,
387         notNullColumn, columnPrefix, typeHandler, flags, null, null, configuration.isLazyLoadingEnabled());
388   }
389 
390   /**
391    * Gets the language driver.
392    *
393    * @param langClass
394    *          the lang class
395    *
396    * @return the language driver
397    *
398    * @deprecated Use {@link Configuration#getLanguageDriver(Class)}
399    */
400   @Deprecated
401   public LanguageDriver getLanguageDriver(Class<? extends LanguageDriver> langClass) {
402     return configuration.getLanguageDriver(langClass);
403   }
404 
405   private Set<String> parseMultipleColumnNames(String columnName) {
406     Set<String> columns = new HashSet<>();
407     if (columnName != null) {
408       if (columnName.indexOf(',') > -1) {
409         StringTokenizer parser = new StringTokenizer(columnName, "{}, ", false);
410         while (parser.hasMoreTokens()) {
411           String column = parser.nextToken();
412           columns.add(column);
413         }
414       } else {
415         columns.add(columnName);
416       }
417     }
418     return columns;
419   }
420 
421   private List<ResultMapping> parseCompositeColumnName(String columnName) {
422     List<ResultMapping> composites = new ArrayList<>();
423     if (columnName != null && (columnName.indexOf('=') > -1 || columnName.indexOf(',') > -1)) {
424       StringTokenizer parser = new StringTokenizer(columnName, "{}=, ", false);
425       while (parser.hasMoreTokens()) {
426         String property = parser.nextToken();
427         String column = parser.nextToken();
428         ResultMapping complexResultMapping = new ResultMapping.Builder(configuration, property, column,
429             (TypeHandler<?>) null).build();
430         composites.add(complexResultMapping);
431       }
432     }
433     return composites;
434   }
435 
436   private Entry<Type, Class<?>> resolveSetterType(Class<?> resultType, String property, Class<?> javaType) {
437     if (javaType != null) {
438       return Map.entry(javaType, javaType);
439     }
440     if (property != null) {
441       MetaClass metaResultType = MetaClass.forClass(resultType, configuration.getReflectorFactory());
442       try {
443         return metaResultType.getGenericSetterType(property);
444       } catch (Exception e) {
445         // Not all property types are resolvable.
446       }
447     }
448     return Map.entry(Object.class, Object.class);
449   }
450 
451   private Class<?> resolveParameterJavaType(Class<?> resultType, String property, Class<?> javaType,
452       JdbcType jdbcType) {
453     if (javaType == null) {
454       if (JdbcType.CURSOR.equals(jdbcType)) {
455         javaType = ResultSet.class;
456       } else if (Map.class.isAssignableFrom(resultType)) {
457         javaType = Object.class;
458       } else {
459         MetaClass metaResultType = MetaClass.forClass(resultType, configuration.getReflectorFactory());
460         javaType = metaResultType.getGetterType(property);
461       }
462     }
463     if (javaType == null) {
464       javaType = Object.class;
465     }
466     return javaType;
467   }
468 }