• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mybatis / mybatis-3 / 4017

02 Dec 2026 01:21PM UTC coverage: 87.564% (+0.1%) from 87.454%
4017

Pull #3809

github

web-flow
Merge de6182685 into 19b82e6ae
Pull Request #3809: Fix JDBC array cleanup when binding or extraction fails

3907 of 4711 branches covered (82.93%)

22 of 22 new or added lines in 1 file covered. (100.0%)

152 existing lines in 10 files now uncovered.

10034 of 11459 relevant lines covered (87.56%)

0.88 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.18
/src/main/java/org/apache/ibatis/builder/MapperBuilderAssistant.java
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.Arrays;
22
import java.util.HashMap;
23
import java.util.HashSet;
24
import java.util.List;
25
import java.util.Map;
26
import java.util.Map.Entry;
27
import java.util.Properties;
28
import java.util.Set;
29
import java.util.regex.Pattern;
30
import java.util.stream.Collectors;
31

32
import org.apache.ibatis.cache.Cache;
33
import org.apache.ibatis.cache.decorators.LruCache;
34
import org.apache.ibatis.cache.impl.PerpetualCache;
35
import org.apache.ibatis.executor.ErrorContext;
36
import org.apache.ibatis.executor.keygen.KeyGenerator;
37
import org.apache.ibatis.mapping.CacheBuilder;
38
import org.apache.ibatis.mapping.Discriminator;
39
import org.apache.ibatis.mapping.MappedStatement;
40
import org.apache.ibatis.mapping.ParameterMap;
41
import org.apache.ibatis.mapping.ParameterMapping;
42
import org.apache.ibatis.mapping.ParameterMode;
43
import org.apache.ibatis.mapping.ResultFlag;
44
import org.apache.ibatis.mapping.ResultMap;
45
import org.apache.ibatis.mapping.ResultMapping;
46
import org.apache.ibatis.mapping.ResultSetType;
47
import org.apache.ibatis.mapping.SqlCommandType;
48
import org.apache.ibatis.mapping.SqlSource;
49
import org.apache.ibatis.mapping.StatementType;
50
import org.apache.ibatis.reflection.MetaClass;
51
import org.apache.ibatis.reflection.ParamNameResolver;
52
import org.apache.ibatis.scripting.LanguageDriver;
53
import org.apache.ibatis.session.Configuration;
54
import org.apache.ibatis.type.JdbcType;
55
import org.apache.ibatis.type.TypeHandler;
56

57
/**
58
 * @author Clinton Begin
59
 */
60
public class MapperBuilderAssistant extends BaseBuilder {
61

62
  private String currentNamespace;
63
  private final String resource;
64
  private Cache currentCache;
65
  private boolean unresolvedCacheRef; // issue #676
66

67
  public MapperBuilderAssistant(Configuration configuration, String resource) {
68
    super(configuration);
1 ✔
69
    ErrorContext.instance().resource(resource);
1 ✔
70
    this.resource = resource;
1 ✔
71
  }
1 ✔
72

73
  public String getCurrentNamespace() {
74
    return currentNamespace;
1 ✔
75
  }
76

77
  public void setCurrentNamespace(String currentNamespace) {
78
    if (currentNamespace == null) {
1 ✔
79
      throw new BuilderException("The mapper element requires a namespace attribute to be specified.");
1 ✔
80
    }
81

82
    if (this.currentNamespace != null && !this.currentNamespace.equals(currentNamespace)) {
1 ✔
83
      throw new BuilderException(
1 ✔
84
          "Wrong namespace. Expected '" + this.currentNamespace + "' but found '" + currentNamespace + "'.");
85
    }
86

87
    this.currentNamespace = currentNamespace;
1 ✔
88
  }
1 ✔
89

90
  public String applyCurrentNamespace(String base, boolean isReference) {
91
    if (base == null) {
1 ✔
92
      return null;
1 ✔
93
    }
94
    if (isReference) {
1 ✔
95
      // is it qualified with any namespace yet?
96
      if (base.contains(".")) {
1 ✔
97
        return base;
1 ✔
98
      }
99
    } else {
100
      // is it qualified with this namespace yet?
101
      if (base.startsWith(currentNamespace + ".")) {
1 ✔
102
        return base;
1 ✔
103
      }
104
      if (base.contains(".")) {
1 ✔
105
        throw new BuilderException("Dots are not allowed in element names, please remove it from " + base);
1 ✔
106
      }
107
    }
108
    return currentNamespace + "." + base;
1 ✔
109
  }
110

111
  public Cache useCacheRef(String namespace) {
112
    if (namespace == null) {
1 ✔
113
      throw new BuilderException("cache-ref element requires a namespace attribute.");
1 ✔
114
    }
115
    try {
116
      unresolvedCacheRef = true;
1 ✔
117
      Cache cache = configuration.getCache(namespace);
1 ✔
118
      if (cache == null) {
1 !
UNCOV
119
        throw new IncompleteElementException("No cache for namespace '" + namespace + "' could be found.");
×
120
      }
121
      currentCache = cache;
1 ✔
122
      unresolvedCacheRef = false;
1 ✔
123
      return cache;
1 ✔
124
    } catch (IllegalArgumentException e) {
1 ✔
125
      throw new IncompleteElementException("No cache for namespace '" + namespace + "' could be found.", e);
1 ✔
126
    }
127
  }
128

129
  public Cache useNewCache(Class<? extends Cache> typeClass, Class<? extends Cache> evictionClass, Long flushInterval,
130
      Integer size, boolean readWrite, boolean blocking, Properties props) {
131
    Cache cache = new CacheBuilder(currentNamespace).implementation(valueOrDefault(typeClass, PerpetualCache.class))
1 ✔
132
        .addDecorator(valueOrDefault(evictionClass, LruCache.class)).clearInterval(flushInterval).size(size)
1 ✔
133
        .readWrite(readWrite).blocking(blocking).properties(props).build();
1 ✔
134
    configuration.addCache(cache);
1 ✔
135
    currentCache = cache;
1 ✔
136
    return cache;
1 ✔
137
  }
138

139
  public ParameterMap addParameterMap(String id, Class<?> parameterClass, List<ParameterMapping> parameterMappings) {
140
    id = applyCurrentNamespace(id, false);
1 ✔
141
    ParameterMap parameterMap = new ParameterMap.Builder(configuration, id, parameterClass, parameterMappings).build();
1 ✔
142
    configuration.addParameterMap(parameterMap);
1 ✔
143
    return parameterMap;
1 ✔
144
  }
145

146
  public ParameterMapping buildParameterMapping(Class<?> parameterType, String property, Class<?> javaType,
147
      JdbcType jdbcType, String resultMap, ParameterMode parameterMode, Class<? extends TypeHandler<?>> typeHandler,
148
      Integer numericScale) {
149
    resultMap = applyCurrentNamespace(resultMap, true);
1 ✔
150

151
    // Class parameterType = parameterMapBuilder.type();
152
    Class<?> javaTypeClass = resolveParameterJavaType(parameterType, property, javaType, jdbcType);
1 ✔
153
    TypeHandler<?> typeHandlerInstance = resolveTypeHandler(javaTypeClass, jdbcType, typeHandler);
1 ✔
154

155
    return new ParameterMapping.Builder(configuration, property, javaTypeClass).jdbcType(jdbcType)
1 ✔
156
        .resultMapId(resultMap).mode(parameterMode).numericScale(numericScale).typeHandler(typeHandlerInstance).build();
1 ✔
157
  }
158

159
  public ResultMap addResultMap(String id, Class<?> type, String extend, Discriminator discriminator,
160
      List<ResultMapping> resultMappings, Boolean autoMapping) {
161
    id = applyCurrentNamespace(id, false);
1 ✔
162
    extend = applyCurrentNamespace(extend, true);
1 ✔
163

164
    if (extend != null) {
1 ✔
165
      if (!configuration.hasResultMap(extend)) {
1 ✔
166
        throw new IncompleteElementException("Could not find a parent resultMap with id '" + extend + "'");
1 ✔
167
      }
168
      ResultMap resultMap = configuration.getResultMap(extend);
1 ✔
169
      List<ResultMapping> extendedResultMappings = new ArrayList<>(resultMap.getResultMappings());
1 ✔
170
      extendedResultMappings.removeAll(resultMappings);
1 ✔
171
      // Remove parent constructor if this resultMap declares a constructor.
172
      boolean declaresConstructor = false;
1 ✔
173
      for (ResultMapping resultMapping : resultMappings) {
1 ✔
174
        if (resultMapping.getFlags().contains(ResultFlag.CONSTRUCTOR)) {
1 ✔
175
          declaresConstructor = true;
1 ✔
176
          break;
1 ✔
177
        }
178
      }
1 ✔
179
      if (declaresConstructor) {
1 ✔
180
        extendedResultMappings.removeIf(resultMapping -> resultMapping.getFlags().contains(ResultFlag.CONSTRUCTOR));
1 ✔
181
      }
182
      resultMappings.addAll(extendedResultMappings);
1 ✔
183
    }
184
    ResultMap resultMap = new ResultMap.Builder(configuration, id, type, resultMappings, autoMapping)
1 ✔
185
        .discriminator(discriminator).build();
1 ✔
186
    configuration.addResultMap(resultMap);
1 ✔
187
    return resultMap;
1 ✔
188
  }
189

190
  public Discriminator buildDiscriminator(Class<?> resultType, String column, Class<?> javaType, JdbcType jdbcType,
191
      Class<? extends TypeHandler<?>> typeHandler, Map<String, String> discriminatorMap) {
192
    ResultMapping resultMapping = buildResultMapping(resultType, null, column, javaType, jdbcType, null, null, null,
1 ✔
193
        null, typeHandler, new ArrayList<>(), null, null, false);
194
    Map<String, String> namespaceDiscriminatorMap = new HashMap<>();
1 ✔
195
    for (Map.Entry<String, String> e : discriminatorMap.entrySet()) {
1 ✔
196
      String resultMap = e.getValue();
1 ✔
197
      resultMap = applyCurrentNamespace(resultMap, true);
1 ✔
198
      namespaceDiscriminatorMap.put(e.getKey(), resultMap);
1 ✔
199
    }
1 ✔
200
    return new Discriminator.Builder(configuration, resultMapping, namespaceDiscriminatorMap).build();
1 ✔
201
  }
202

203
  public MappedStatement addMappedStatement(String id, SqlSource sqlSource, StatementType statementType,
204
      SqlCommandType sqlCommandType, Integer fetchSize, Integer timeout, String parameterMap, Class<?> parameterType,
205
      String resultMap, Class<?> resultType, ResultSetType resultSetType, boolean flushCache, boolean useCache,
206
      boolean resultOrdered, KeyGenerator keyGenerator, String keyProperty, String keyColumn, String databaseId,
207
      LanguageDriver lang, String resultSets, boolean dirtySelect, ParamNameResolver paramNameResolver) {
208

209
    if (unresolvedCacheRef) {
1 ✔
210
      throw new IncompleteElementException("Cache-ref not yet resolved");
1 ✔
211
    }
212

213
    id = applyCurrentNamespace(id, false);
1 ✔
214

215
    MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType)
1 ✔
216
        .resource(resource).fetchSize(fetchSize).timeout(timeout).statementType(statementType)
1 ✔
217
        .keyGenerator(keyGenerator).keyProperty(keyProperty).keyColumn(keyColumn).databaseId(databaseId).lang(lang)
1 ✔
218
        .resultOrdered(resultOrdered).resultSets(resultSets)
1 ✔
219
        .resultMaps(getStatementResultMaps(resultMap, resultType, id)).resultSetType(resultSetType)
1 ✔
220
        .flushCacheRequired(flushCache).useCache(useCache).cache(currentCache).dirtySelect(dirtySelect)
1 ✔
221
        .paramNameResolver(paramNameResolver);
1 ✔
222

223
    ParameterMap statementParameterMap = getStatementParameterMap(parameterMap, parameterType, id);
1 ✔
224
    if (statementParameterMap != null) {
1 ✔
225
      statementBuilder.parameterMap(statementParameterMap);
1 ✔
226
    }
227

228
    MappedStatement statement = statementBuilder.build();
1 ✔
229
    configuration.addMappedStatement(statement);
1 ✔
230
    return statement;
1 ✔
231
  }
232

233
  /**
234
   * Backward compatibility signature 'addMappedStatement'.
235
   *
236
   * @param id
237
   *          the id
238
   * @param sqlSource
239
   *          the sql source
240
   * @param statementType
241
   *          the statement type
242
   * @param sqlCommandType
243
   *          the sql command type
244
   * @param fetchSize
245
   *          the fetch size
246
   * @param timeout
247
   *          the timeout
248
   * @param parameterMap
249
   *          the parameter map
250
   * @param parameterType
251
   *          the parameter type
252
   * @param resultMap
253
   *          the result map
254
   * @param resultType
255
   *          the result type
256
   * @param resultSetType
257
   *          the result set type
258
   * @param flushCache
259
   *          the flush cache
260
   * @param useCache
261
   *          the use cache
262
   * @param resultOrdered
263
   *          the result ordered
264
   * @param keyGenerator
265
   *          the key generator
266
   * @param keyProperty
267
   *          the key property
268
   * @param keyColumn
269
   *          the key column
270
   * @param databaseId
271
   *          the database id
272
   * @param lang
273
   *          the lang
274
   *
275
   * @return the mapped statement
276
   */
277
  public MappedStatement addMappedStatement(String id, SqlSource sqlSource, StatementType statementType,
278
      SqlCommandType sqlCommandType, Integer fetchSize, Integer timeout, String parameterMap, Class<?> parameterType,
279
      String resultMap, Class<?> resultType, ResultSetType resultSetType, boolean flushCache, boolean useCache,
280
      boolean resultOrdered, KeyGenerator keyGenerator, String keyProperty, String keyColumn, String databaseId,
281
      LanguageDriver lang, String resultSets) {
UNCOV
282
    return addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, parameterMap,
×
283
        parameterType, resultMap, resultType, resultSetType, flushCache, useCache, resultOrdered, keyGenerator,
284
        keyProperty, keyColumn, databaseId, lang, null, false, null);
285
  }
286

287
  public MappedStatement addMappedStatement(String id, SqlSource sqlSource, StatementType statementType,
288
      SqlCommandType sqlCommandType, Integer fetchSize, Integer timeout, String parameterMap, Class<?> parameterType,
289
      String resultMap, Class<?> resultType, ResultSetType resultSetType, boolean flushCache, boolean useCache,
290
      boolean resultOrdered, KeyGenerator keyGenerator, String keyProperty, String keyColumn, String databaseId,
291
      LanguageDriver lang) {
UNCOV
292
    return addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, parameterMap,
×
293
        parameterType, resultMap, resultType, resultSetType, flushCache, useCache, resultOrdered, keyGenerator,
294
        keyProperty, keyColumn, databaseId, lang, null);
295
  }
296

297
  private <T> T valueOrDefault(T value, T defaultValue) {
298
    return value == null ? defaultValue : value;
1 !
299
  }
300

301
  private ParameterMap getStatementParameterMap(String parameterMapName, Class<?> parameterTypeClass,
302
      String statementId) {
303
    parameterMapName = applyCurrentNamespace(parameterMapName, true);
1 ✔
304
    ParameterMap parameterMap = null;
1 ✔
305
    if (parameterMapName != null) {
1 ✔
306
      try {
307
        parameterMap = configuration.getParameterMap(parameterMapName);
1 ✔
308
      } catch (IllegalArgumentException e) {
1 ✔
309
        throw new IncompleteElementException("Could not find parameter map " + parameterMapName, e);
1 ✔
310
      }
1 ✔
311
    } else if (parameterTypeClass != null) {
1 ✔
312
      parameterMap = ParameterMap.buildEmpty(statementId + "-Inline", parameterTypeClass);
1 ✔
313
    }
314
    return parameterMap;
1 ✔
315
  }
316

317
  private List<ResultMap> getStatementResultMaps(String resultMap, Class<?> resultType, String statementId) {
318
    resultMap = applyCurrentNamespace(resultMap, true);
1 ✔
319

320
    List<ResultMap> resultMaps = new ArrayList<>();
1 ✔
321
    if (resultMap != null) {
1 ✔
322
      String[] resultMapNames = resultMap.split(",");
1 ✔
323
      for (String resultMapName : resultMapNames) {
1 ✔
324
        try {
325
          resultMaps.add(configuration.getResultMap(resultMapName.trim()));
1 ✔
326
        } catch (IllegalArgumentException e) {
1 ✔
327
          throw new IncompleteElementException(
1 ✔
328
              "Could not find result map '" + resultMapName + "' referenced from '" + statementId + "'", e);
329
        }
1 ✔
330
      }
331
    } else if (resultType != null) {
1 ✔
332
      resultMaps.add(ResultMap.buildEmpty(configuration, statementId + "-Inline", resultType));
1 ✔
333
    }
334
    return resultMaps;
1 ✔
335
  }
336

337
  public ResultMapping buildResultMapping(Class<?> resultType, String property, String column, Class<?> javaType,
338
      JdbcType jdbcType, String nestedSelect, String nestedResultMap, String notNullColumn, String columnPrefix,
339
      Class<? extends TypeHandler<?>> typeHandler, List<ResultFlag> flags, String resultSet, String foreignColumn,
340
      boolean lazy) {
341
    Entry<Type, Class<?>> setterType = resolveSetterType(resultType, property, javaType);
1 ✔
342
    TypeHandler<?> typeHandlerInstance = resolveTypeHandler(setterType.getKey(), jdbcType, typeHandler);
1 ✔
343
    List<ResultMapping> composites;
344
    if ((nestedSelect == null || nestedSelect.isEmpty()) && (foreignColumn == null || foreignColumn.isEmpty())) {
1 !
345
      composites = List.of();
1 ✔
346
    } else {
347
      composites = parseCompositeColumnName(column);
1 ✔
348
    }
349
    return new ResultMapping.Builder(configuration, property, column, setterType.getValue()).jdbcType(jdbcType)
1 ✔
350
        .nestedQueryId(applyCurrentNamespace(nestedSelect, true))
1 ✔
351
        .nestedResultMapId(applyCurrentNamespace(nestedResultMap, true)).resultSet(resultSet)
1 ✔
352
        .typeHandler(typeHandlerInstance).flags(flags == null ? new ArrayList<>() : flags).composites(composites)
1 !
353
        .notNullColumns(parseMultipleColumnNames(notNullColumn)).columnPrefix(columnPrefix).foreignColumn(foreignColumn)
1 ✔
354
        .lazy(lazy).build();
1 ✔
355
  }
356

357
  /**
358
   * Backward compatibility signature 'buildResultMapping'.
359
   *
360
   * @param resultType
361
   *          the result type
362
   * @param property
363
   *          the property
364
   * @param column
365
   *          the column
366
   * @param javaType
367
   *          the java type
368
   * @param jdbcType
369
   *          the jdbc type
370
   * @param nestedSelect
371
   *          the nested select
372
   * @param nestedResultMap
373
   *          the nested result map
374
   * @param notNullColumn
375
   *          the not null column
376
   * @param columnPrefix
377
   *          the column prefix
378
   * @param typeHandler
379
   *          the type handler
380
   * @param flags
381
   *          the flags
382
   *
383
   * @return the result mapping
384
   */
385
  public ResultMapping buildResultMapping(Class<?> resultType, String property, String column, Class<?> javaType,
386
      JdbcType jdbcType, String nestedSelect, String nestedResultMap, String notNullColumn, String columnPrefix,
387
      Class<? extends TypeHandler<?>> typeHandler, List<ResultFlag> flags) {
UNCOV
388
    return buildResultMapping(resultType, property, column, javaType, jdbcType, nestedSelect, nestedResultMap,
×
UNCOV
389
        notNullColumn, columnPrefix, typeHandler, flags, null, null, configuration.isLazyLoadingEnabled());
×
390
  }
391

392
  /**
393
   * Gets the language driver.
394
   *
395
   * @param langClass
396
   *          the lang class
397
   *
398
   * @return the language driver
399
   *
400
   * @deprecated Use {@link Configuration#getLanguageDriver(Class)}
401
   */
402
  @Deprecated
403
  public LanguageDriver getLanguageDriver(Class<? extends LanguageDriver> langClass) {
UNCOV
404
    return configuration.getLanguageDriver(langClass);
×
405
  }
406

407
  private Set<String> parseMultipleColumnNames(final String columnName) {
408
    final Set<String> columns = new HashSet<>();
1 ✔
409
    if (columnName != null) {
1 ✔
410
      if (columnName.contains(",")) {
1 ✔
411
        Pattern.compile("[{}, ]+").splitAsStream(columnName).filter(column -> !column.isEmpty()).forEach(columns::add);
1 ✔
412
      } else {
413
        columns.add(columnName);
1 ✔
414
      }
415
    }
416
    return columns;
1 ✔
417
  }
418

419
  private List<ResultMapping> parseCompositeColumnName(final String columnName) {
420
    final List<ResultMapping> composites = new ArrayList<>();
1 ✔
421
    if (columnName != null && (columnName.contains("=") || columnName.contains(","))) {
1 !
422
      final String[] columns = Pattern.compile("[{},= ]+").split(columnName);
1 ✔
423
      final List<String> tokens = Arrays.stream(columns).filter(column -> !column.isEmpty())
1 ✔
424
          .collect(Collectors.toList());
1 ✔
425

426
      for (int i = 0; i + 1 < tokens.size(); i += 2) {
1 ✔
427
        final String property = tokens.get(i);
1 ✔
428
        final String column = tokens.get(i + 1);
1 ✔
429
        final ResultMapping complexResultMapping = new ResultMapping.Builder(configuration, property, column,
1 ✔
430
            (TypeHandler<?>) null).build();
1 ✔
431
        composites.add(complexResultMapping);
1 ✔
432
      }
433
    }
434
    return composites;
1 ✔
435
  }
436

437
  private Entry<Type, Class<?>> resolveSetterType(Class<?> resultType, String property, Class<?> javaType) {
438
    if (javaType != null) {
1 ✔
439
      return Map.entry(javaType, javaType);
1 ✔
440
    }
441
    if (property != null) {
1 ✔
442
      MetaClass metaResultType = MetaClass.forClass(resultType, configuration.getReflectorFactory());
1 ✔
443
      try {
444
        return metaResultType.getGenericSetterType(property);
1 ✔
445
      } catch (Exception e) {
1 ✔
446
        // Not all property types are resolvable.
447
      }
448
    }
449
    return Map.entry(Object.class, Object.class);
1 ✔
450
  }
451

452
  private Class<?> resolveParameterJavaType(Class<?> resultType, String property, Class<?> javaType,
453
      JdbcType jdbcType) {
454
    if (javaType == null) {
1 !
455
      if (JdbcType.CURSOR.equals(jdbcType)) {
1 !
UNCOV
456
        javaType = ResultSet.class;
×
457
      } else if (Map.class.isAssignableFrom(resultType)) {
1 ✔
458
        javaType = Object.class;
1 ✔
459
      } else {
460
        MetaClass metaResultType = MetaClass.forClass(resultType, configuration.getReflectorFactory());
1 ✔
461
        javaType = metaResultType.getGetterType(property);
1 ✔
462
      }
463
    }
464
    if (javaType == null) {
1 !
UNCOV
465
      javaType = Object.class;
×
466
    }
467
    return javaType;
1 ✔
468
  }
469
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc