• 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

91.09
/src/main/java/org/apache/ibatis/executor/resultset/DefaultResultSetHandler.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.executor.resultset;
17

18
import java.lang.reflect.Constructor;
19
import java.lang.reflect.Parameter;
20
import java.lang.reflect.Type;
21
import java.sql.CallableStatement;
22
import java.sql.ResultSet;
23
import java.sql.SQLException;
24
import java.sql.Statement;
25
import java.text.MessageFormat;
26
import java.util.ArrayList;
27
import java.util.Arrays;
28
import java.util.Collection;
29
import java.util.HashMap;
30
import java.util.HashSet;
31
import java.util.IdentityHashMap;
32
import java.util.List;
33
import java.util.Locale;
34
import java.util.Map;
35
import java.util.Optional;
36
import java.util.Set;
37

38
import org.apache.ibatis.annotations.AutomapConstructor;
39
import org.apache.ibatis.annotations.Param;
40
import org.apache.ibatis.binding.MapperMethod.ParamMap;
41
import org.apache.ibatis.cache.CacheKey;
42
import org.apache.ibatis.cursor.Cursor;
43
import org.apache.ibatis.cursor.defaults.DefaultCursor;
44
import org.apache.ibatis.executor.ErrorContext;
45
import org.apache.ibatis.executor.Executor;
46
import org.apache.ibatis.executor.ExecutorException;
47
import org.apache.ibatis.executor.loader.ResultLoader;
48
import org.apache.ibatis.executor.loader.ResultLoaderMap;
49
import org.apache.ibatis.executor.parameter.ParameterHandler;
50
import org.apache.ibatis.executor.result.DefaultResultContext;
51
import org.apache.ibatis.executor.result.DefaultResultHandler;
52
import org.apache.ibatis.executor.result.ResultMapException;
53
import org.apache.ibatis.mapping.BoundSql;
54
import org.apache.ibatis.mapping.Discriminator;
55
import org.apache.ibatis.mapping.MappedStatement;
56
import org.apache.ibatis.mapping.ParameterMapping;
57
import org.apache.ibatis.mapping.ParameterMode;
58
import org.apache.ibatis.mapping.ResultMap;
59
import org.apache.ibatis.mapping.ResultMapping;
60
import org.apache.ibatis.reflection.MetaClass;
61
import org.apache.ibatis.reflection.MetaObject;
62
import org.apache.ibatis.reflection.ReflectorFactory;
63
import org.apache.ibatis.reflection.factory.ObjectFactory;
64
import org.apache.ibatis.session.AutoMappingBehavior;
65
import org.apache.ibatis.session.Configuration;
66
import org.apache.ibatis.session.ResultContext;
67
import org.apache.ibatis.session.ResultHandler;
68
import org.apache.ibatis.session.RowBounds;
69
import org.apache.ibatis.type.JdbcType;
70
import org.apache.ibatis.type.ObjectTypeHandler;
71
import org.apache.ibatis.type.TypeHandler;
72
import org.apache.ibatis.type.TypeHandlerRegistry;
73

74
/**
75
 * @author Clinton Begin
76
 * @author Eduardo Macarron
77
 * @author Iwao AVE!
78
 * @author Kazuki Shimizu
79
 * @author Willie Scholtz
80
 */
81
public class DefaultResultSetHandler implements ResultSetHandler {
82

83
  private static final Object DEFERRED = new Object();
1 ✔
84

85
  private final Executor executor;
86
  private final Configuration configuration;
87
  private final MappedStatement mappedStatement;
88
  private final RowBounds rowBounds;
89
  private final ParameterHandler parameterHandler;
90
  private final ResultHandler<?> resultHandler;
91
  private final BoundSql boundSql;
92
  private final TypeHandlerRegistry typeHandlerRegistry;
93
  private final ObjectFactory objectFactory;
94
  private final ReflectorFactory reflectorFactory;
95

96
  // pending creations property tracker
97
  private final Map<Object, PendingRelation> pendingPccRelations = new IdentityHashMap<>();
1 ✔
98

99
  // nested resultMaps
100
  private final Map<CacheKey, Object> nestedResultObjects = new HashMap<>();
1 ✔
101
  private final Map<String, Object> ancestorObjects = new HashMap<>();
1 ✔
102
  private Object previousRowValue;
103

104
  // multiple resultSets
105
  private final Map<String, ResultMapping> nextResultMaps = new HashMap<>();
1 ✔
106
  private final Map<CacheKey, List<PendingRelation>> pendingRelations = new HashMap<>();
1 ✔
107

108
  // Cached AutoMappings
109
  private final Map<String, List<UnMappedColumnAutoMapping>> autoMappingsCache = new HashMap<>();
1 ✔
110
  private final Map<String, List<String>> constructorAutoMappingColumns = new HashMap<>();
1 ✔
111

112
  // temporary marking flag that indicate using constructor mapping (use field to reduce memory usage)
113
  private boolean useConstructorMappings;
114

115
  private static class PendingRelation {
116
    public MetaObject metaObject;
117
    public ResultMapping propertyMapping;
118
  }
119

120
  private static class UnMappedColumnAutoMapping {
121
    private final String column;
122
    private final String property;
123
    private final TypeHandler<?> typeHandler;
124
    private final boolean primitive;
125

126
    public UnMappedColumnAutoMapping(String column, String property, TypeHandler<?> typeHandler, boolean primitive) {
1 ✔
127
      this.column = column;
1 ✔
128
      this.property = property;
1 ✔
129
      this.typeHandler = typeHandler;
1 ✔
130
      this.primitive = primitive;
1 ✔
131
    }
1 ✔
132
  }
133

134
  public DefaultResultSetHandler(Executor executor, MappedStatement mappedStatement, ParameterHandler parameterHandler,
135
      ResultHandler<?> resultHandler, BoundSql boundSql, RowBounds rowBounds) {
1 ✔
136
    this.executor = executor;
1 ✔
137
    this.configuration = mappedStatement.getConfiguration();
1 ✔
138
    this.mappedStatement = mappedStatement;
1 ✔
139
    this.rowBounds = rowBounds;
1 ✔
140
    this.parameterHandler = parameterHandler;
1 ✔
141
    this.boundSql = boundSql;
1 ✔
142
    this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
1 ✔
143
    this.objectFactory = configuration.getObjectFactory();
1 ✔
144
    this.reflectorFactory = configuration.getReflectorFactory();
1 ✔
145
    this.resultHandler = resultHandler;
1 ✔
146
  }
1 ✔
147

148
  //
149
  // HANDLE OUTPUT PARAMETER
150
  //
151

152
  @Override
153
  public void handleOutputParameters(CallableStatement cs) throws SQLException {
154
    final Object parameterObject = parameterHandler.getParameterObject();
1 ✔
155
    final MetaObject metaParam = configuration.newMetaObject(parameterObject);
1 ✔
156
    final List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
1 ✔
157
    for (int i = 0; i < parameterMappings.size(); i++) {
1 ✔
158
      final ParameterMapping parameterMapping = parameterMappings.get(i);
1 ✔
159
      if (parameterMapping.getMode() == ParameterMode.OUT || parameterMapping.getMode() == ParameterMode.INOUT) {
1 !
160
        if (ResultSet.class.equals(parameterMapping.getJavaType())) {
1 !
161
          handleRefCursorOutputParameter((ResultSet) cs.getObject(i + 1), parameterMapping, metaParam);
×
162
        } else {
163
          final String property = parameterMapping.getProperty();
1 ✔
164
          TypeHandler<?> typeHandler = parameterMapping.getTypeHandler();
1 ✔
165
          if (typeHandler == null) {
1 ✔
166
            Type javaType = parameterMapping.getJavaType();
1 ✔
167
            if (javaType == null || javaType == Object.class) {
1 !
168
              javaType = metaParam.getGenericSetterType(property).getKey();
1 ✔
169
            }
170
            JdbcType jdbcType = parameterMapping.getJdbcType();
1 ✔
171
            typeHandler = typeHandlerRegistry.getTypeHandler(javaType, jdbcType, null);
1 ✔
172
            if (typeHandler == null) {
1 !
173
              typeHandler = typeHandlerRegistry.getTypeHandler(jdbcType);
1 ✔
174
              if (typeHandler == null) {
1 !
175
                typeHandler = ObjectTypeHandler.INSTANCE;
×
176
              }
177
            }
178
          }
179
          metaParam.setValue(property, typeHandler.getResult(cs, i + 1));
1 ✔
180
        }
181
      }
182
    }
183
  }
1 ✔
184

185
  private void handleRefCursorOutputParameter(ResultSet rs, ParameterMapping parameterMapping, MetaObject metaParam)
186
      throws SQLException {
187
    if (rs == null) {
×
188
      return;
×
189
    }
190
    try {
191
      final String resultMapId = parameterMapping.getResultMapId();
×
192
      final ResultMap resultMap = configuration.getResultMap(resultMapId);
×
193
      final ResultSetWrapper rsw = new ResultSetWrapper(rs, configuration);
×
194
      if (this.resultHandler == null) {
×
195
        final DefaultResultHandler resultHandler = new DefaultResultHandler(objectFactory);
×
196
        handleRowValues(rsw, resultMap, resultHandler, new RowBounds(), null);
×
197
        metaParam.setValue(parameterMapping.getProperty(), resultHandler.getResultList());
×
198
      } else {
×
199
        handleRowValues(rsw, resultMap, resultHandler, new RowBounds(), null);
×
200
      }
201
    } finally {
202
      // issue #228 (close resultSets)
203
      closeResultSet(rs);
×
204
    }
205
  }
×
206

207
  //
208
  // HANDLE RESULT SETS
209
  //
210
  @Override
211
  public List<Object> handleResultSets(Statement stmt) throws SQLException {
212
    ErrorContext.instance().activity("handling results").object(mappedStatement.getId());
1 ✔
213

214
    final List<Object> multipleResults = new ArrayList<>();
1 ✔
215

216
    int resultSetCount = 0;
1 ✔
217
    ResultSetWrapper rsw = getFirstResultSet(stmt);
1 ✔
218

219
    List<ResultMap> resultMaps = mappedStatement.getResultMaps();
1 ✔
220
    int resultMapCount = resultMaps.size();
1 ✔
221
    validateResultMapsCount(rsw, resultMapCount);
1 ✔
222
    while (rsw != null && resultMapCount > resultSetCount) {
1 ✔
223
      ResultMap resultMap = resultMaps.get(resultSetCount);
1 ✔
224
      handleResultSet(rsw, resultMap, multipleResults, null);
1 ✔
225
      rsw = getNextResultSet(stmt);
1 ✔
226
      cleanUpAfterHandlingResultSet();
1 ✔
227
      resultSetCount++;
1 ✔
228
    }
1 ✔
229

230
    String[] resultSets = mappedStatement.getResultSets();
1 ✔
231
    if (resultSets != null) {
1 ✔
232
      while (rsw != null && resultSetCount < resultSets.length) {
1 !
233
        ResultMapping parentMapping = nextResultMaps.get(resultSets[resultSetCount]);
1 ✔
234
        if (parentMapping != null) {
1 !
235
          String nestedResultMapId = parentMapping.getNestedResultMapId();
1 ✔
236
          ResultMap resultMap = configuration.getResultMap(nestedResultMapId);
1 ✔
237
          handleResultSet(rsw, resultMap, null, parentMapping);
1 ✔
238
        }
239
        rsw = getNextResultSet(stmt);
1 ✔
240
        cleanUpAfterHandlingResultSet();
1 ✔
241
        resultSetCount++;
1 ✔
242
      }
1 ✔
243
    }
244

245
    return collapseSingleResultList(multipleResults);
1 ✔
246
  }
247

248
  @Override
249
  public <E> Cursor<E> handleCursorResultSets(Statement stmt) throws SQLException {
250
    ErrorContext.instance().activity("handling cursor results").object(mappedStatement.getId());
1 ✔
251

252
    ResultSetWrapper rsw = getFirstResultSet(stmt);
1 ✔
253

254
    List<ResultMap> resultMaps = mappedStatement.getResultMaps();
1 ✔
255

256
    int resultMapCount = resultMaps.size();
1 ✔
257
    validateResultMapsCount(rsw, resultMapCount);
1 ✔
258
    if (resultMapCount != 1) {
1 !
259
      throw new ExecutorException("Cursor results cannot be mapped to multiple resultMaps");
×
260
    }
261

262
    ResultMap resultMap = resultMaps.get(0);
1 ✔
263
    return new DefaultCursor<>(this, resultMap, rsw, rowBounds);
1 ✔
264
  }
265

266
  private ResultSetWrapper getFirstResultSet(Statement stmt) throws SQLException {
267
    ResultSet rs = null;
1 ✔
268
    SQLException e1 = null;
1 ✔
269

270
    try {
271
      rs = stmt.getResultSet();
1 ✔
272
    } catch (SQLException e) {
×
273
      // Oracle throws ORA-17283 for implicit cursor
274
      e1 = e;
×
275
    }
1 ✔
276

277
    try {
278
      while (rs == null) {
1 ✔
279
        // move forward to get the first resultSet in case the driver
280
        // doesn't return the resultSet as the first result (HSQLDB)
281
        if (stmt.getMoreResults()) {
1 !
282
          rs = stmt.getResultSet();
×
283
        } else if (stmt.getUpdateCount() == -1) {
1 !
284
          // no more results. Must be no resultSet
285
          break;
1 ✔
286
        }
287
      }
288
    } catch (SQLException e) {
×
289
      throw e1 != null ? e1 : e;
×
290
    }
1 ✔
291

292
    return rs != null ? new ResultSetWrapper(rs, configuration) : null;
1 ✔
293
  }
294

295
  private ResultSetWrapper getNextResultSet(Statement stmt) {
296
    // Making this method tolerant of bad JDBC drivers
297
    try {
298
      // We stopped checking DatabaseMetaData#supportsMultipleResultSets()
299
      // because Oracle driver (incorrectly) returns false
300

301
      // Crazy Standard JDBC way of determining if there are more results
302
      // DO NOT try to 'improve' the condition even if IDE tells you to!
303
      // It's important that getUpdateCount() is called here.
304
      if (!(!stmt.getMoreResults() && stmt.getUpdateCount() == -1)) {
1 ✔
305
        ResultSet rs = stmt.getResultSet();
1 ✔
306
        if (rs == null) {
1 !
307
          return getNextResultSet(stmt);
×
308
        } else {
309
          return new ResultSetWrapper(rs, configuration);
1 ✔
310
        }
311
      }
312
    } catch (Exception e) {
×
313
      // Intentionally ignored.
314
    }
1 ✔
315
    return null;
1 ✔
316
  }
317

318
  private void closeResultSet(ResultSet rs) {
319
    try {
320
      if (rs != null) {
1 !
321
        rs.close();
1 ✔
322
      }
323
    } catch (SQLException e) {
×
324
      // ignore
325
    }
1 ✔
326
  }
1 ✔
327

328
  private void cleanUpAfterHandlingResultSet() {
329
    nestedResultObjects.clear();
1 ✔
330
  }
1 ✔
331

332
  private void validateResultMapsCount(ResultSetWrapper rsw, int resultMapCount) {
333
    if (rsw != null && resultMapCount < 1) {
1 ✔
334
      throw new ExecutorException(
1 ✔
335
          "A query was run and no Result Maps were found for the Mapped Statement '" + mappedStatement.getId()
1 ✔
336
              + "'. 'resultType' or 'resultMap' must be specified when there is no corresponding method.");
337
    }
338
  }
1 ✔
339

340
  private void handleResultSet(ResultSetWrapper rsw, ResultMap resultMap, List<Object> multipleResults,
341
      ResultMapping parentMapping) throws SQLException {
342
    try {
343
      if (parentMapping != null) {
1 ✔
344
        handleRowValues(rsw, resultMap, null, RowBounds.DEFAULT, parentMapping);
1 ✔
345
      } else if (resultHandler == null) {
1 ✔
346
        DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory);
1 ✔
347
        handleRowValues(rsw, resultMap, defaultResultHandler, rowBounds, null);
1 ✔
348
        multipleResults.add(defaultResultHandler.getResultList());
1 ✔
349
      } else {
1 ✔
350
        handleRowValues(rsw, resultMap, resultHandler, rowBounds, null);
1 ✔
351
      }
352
    } finally {
353
      // issue #228 (close resultSets)
354
      closeResultSet(rsw.getResultSet());
1 ✔
355
    }
356
  }
1 ✔
357

358
  @SuppressWarnings("unchecked")
359
  private List<Object> collapseSingleResultList(List<Object> multipleResults) {
360
    return multipleResults.size() == 1 ? (List<Object>) multipleResults.get(0) : multipleResults;
1 ✔
361
  }
362

363
  //
364
  // HANDLE ROWS FOR SIMPLE RESULTMAP
365
  //
366

367
  public void handleRowValues(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler,
368
      RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
369
    if (resultMap.hasNestedResultMaps()) {
1 ✔
370
      ensureNoRowBounds();
1 ✔
371
      checkResultHandler();
1 ✔
372
      handleRowValuesForNestedResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
1 ✔
373
    } else {
374
      handleRowValuesForSimpleResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
1 ✔
375
    }
376
  }
1 ✔
377

378
  private void ensureNoRowBounds() {
379
    if (configuration.isSafeRowBoundsEnabled() && rowBounds != null
1 !
380
        && (rowBounds.getLimit() < RowBounds.NO_ROW_LIMIT || rowBounds.getOffset() > RowBounds.NO_ROW_OFFSET)) {
×
381
      throw new ExecutorException(
×
382
          "Mapped Statements with nested result mappings cannot be safely constrained by RowBounds. "
383
              + "Use safeRowBoundsEnabled=false setting to bypass this check.");
384
    }
385
  }
1 ✔
386

387
  protected void checkResultHandler() {
388
    if (resultHandler != null && configuration.isSafeResultHandlerEnabled() && !mappedStatement.isResultOrdered()) {
1 !
389
      throw new ExecutorException(
1 ✔
390
          "Mapped Statements with nested result mappings cannot be safely used with a custom ResultHandler. "
391
              + "Use safeResultHandlerEnabled=false setting to bypass this check "
392
              + "or ensure your statement returns ordered data and set resultOrdered=true on it.");
393
    }
394
  }
1 ✔
395

396
  private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap,
397
      ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
398
    final boolean useCollectionConstructorInjection = resultMap.hasResultMapsUsingConstructorCollection();
1 ✔
399

400
    DefaultResultContext<Object> resultContext = new DefaultResultContext<>();
1 ✔
401
    ResultSet resultSet = rsw.getResultSet();
1 ✔
402
    skipRows(resultSet, rowBounds);
1 ✔
403
    while (shouldProcessMoreRows(resultContext, rowBounds) && !resultSet.isClosed() && resultSet.next()) {
1 ✔
404
      ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rsw, resultMap, null);
1 ✔
405
      Object rowValue = getRowValue(rsw, discriminatedResultMap, null, null);
1 ✔
406
      if (!useCollectionConstructorInjection) {
1 !
407
        storeObject(resultHandler, resultContext, rowValue, parentMapping, resultSet);
1 ✔
408
      } else {
409
        if (!(rowValue instanceof PendingConstructorCreation)) {
×
410
          throw new ExecutorException("Expected result object to be a pending constructor creation!");
×
411
        }
412

413
        createAndStorePendingCreation(resultHandler, resultSet, resultContext, (PendingConstructorCreation) rowValue);
×
414
      }
415
    }
1 ✔
416
  }
1 ✔
417

418
  private void storeObject(ResultHandler<?> resultHandler, DefaultResultContext<Object> resultContext, Object rowValue,
419
      ResultMapping parentMapping, ResultSet rs) throws SQLException {
420
    if (parentMapping != null) {
1 ✔
421
      linkToParents(rs, parentMapping, rowValue);
1 ✔
422
      return;
1 ✔
423
    }
424

425
    if (pendingPccRelations.containsKey(rowValue)) {
1 ✔
426
      createPendingConstructorCreations(rowValue);
1 ✔
427
    }
428

429
    callResultHandler(resultHandler, resultContext, rowValue);
1 ✔
430
  }
1 ✔
431

432
  @SuppressWarnings("unchecked" /* because ResultHandler<?> is always ResultHandler<Object> */)
433
  private void callResultHandler(ResultHandler<?> resultHandler, DefaultResultContext<Object> resultContext,
434
      Object rowValue) {
435
    resultContext.nextResultObject(rowValue);
1 ✔
436
    ((ResultHandler<Object>) resultHandler).handleResult(resultContext);
1 ✔
437
  }
1 ✔
438

439
  private boolean shouldProcessMoreRows(ResultContext<?> context, RowBounds rowBounds) {
440
    return !context.isStopped() && context.getResultCount() < rowBounds.getLimit();
1 ✔
441
  }
442

443
  private void skipRows(ResultSet rs, RowBounds rowBounds) throws SQLException {
444
    if (rs.getType() != ResultSet.TYPE_FORWARD_ONLY) {
1 ✔
445
      if (rowBounds.getOffset() != RowBounds.NO_ROW_OFFSET) {
1 !
446
        rs.absolute(rowBounds.getOffset());
1 ✔
447
      }
448
    } else {
449
      for (int i = 0; i < rowBounds.getOffset(); i++) {
1 ✔
450
        if (!rs.next()) {
1 ✔
451
          break;
1 ✔
452
        }
453
      }
454
    }
455
  }
1 ✔
456

457
  //
458
  // GET VALUE FROM ROW FOR SIMPLE RESULT MAP
459
  //
460

461
  private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix, CacheKey parentRowKey)
462
      throws SQLException {
463
    final ResultLoaderMap lazyLoader = new ResultLoaderMap();
1 ✔
464
    Object rowValue = createResultObject(rsw, resultMap, lazyLoader, columnPrefix, parentRowKey);
1 ✔
465
    if (rowValue != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
1 ✔
466
      final MetaObject metaObject = configuration.newMetaObject(rowValue);
1 ✔
467
      boolean foundValues = this.useConstructorMappings;
1 ✔
468
      if (shouldApplyAutomaticMappings(resultMap, false)) {
1 ✔
469
        foundValues = applyAutomaticMappings(rsw, resultMap, metaObject, columnPrefix) || foundValues;
1 ✔
470
      }
471
      foundValues = applyPropertyMappings(rsw, resultMap, metaObject, lazyLoader, columnPrefix) || foundValues;
1 ✔
472
      foundValues = lazyLoader.size() > 0 || foundValues;
1 ✔
473
      rowValue = foundValues || configuration.isReturnInstanceForEmptyRow() ? rowValue : null;
1 ✔
474
    }
475

476
    if (parentRowKey != null) {
1 ✔
477
      // found a simple object/primitive in pending constructor creation that will need linking later
478
      final CacheKey rowKey = createRowKey(resultMap, rsw, columnPrefix);
1 ✔
479
      final CacheKey combinedKey = combineKeys(rowKey, parentRowKey);
1 ✔
480

481
      if (combinedKey != CacheKey.NULL_CACHE_KEY) {
1 ✔
482
        nestedResultObjects.put(combinedKey, rowValue);
1 ✔
483
      }
484
    }
485

486
    return rowValue;
1 ✔
487
  }
488

489
  //
490
  // GET VALUE FROM ROW FOR NESTED RESULT MAP
491
  //
492

493
  private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap, CacheKey combinedKey, String columnPrefix,
494
      Object partialObject) throws SQLException {
495
    final String resultMapId = resultMap.getId();
1 ✔
496
    Object rowValue = partialObject;
1 ✔
497
    if (rowValue != null) {
1 ✔
498
      final MetaObject metaObject = configuration.newMetaObject(rowValue);
1 ✔
499
      putAncestor(rowValue, resultMapId);
1 ✔
500
      applyNestedResultMappings(rsw, resultMap, metaObject, columnPrefix, combinedKey, false);
1 ✔
501
      ancestorObjects.remove(resultMapId);
1 ✔
502
    } else {
1 ✔
503
      final ResultLoaderMap lazyLoader = new ResultLoaderMap();
1 ✔
504
      rowValue = createResultObject(rsw, resultMap, lazyLoader, columnPrefix, combinedKey);
1 ✔
505
      if (rowValue != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
1 ✔
506
        final MetaObject metaObject = configuration.newMetaObject(rowValue);
1 ✔
507
        boolean foundValues = this.useConstructorMappings;
1 ✔
508
        if (shouldApplyAutomaticMappings(resultMap, true)) {
1 ✔
509
          foundValues = applyAutomaticMappings(rsw, resultMap, metaObject, columnPrefix) || foundValues;
1 !
510
        }
511
        foundValues = applyPropertyMappings(rsw, resultMap, metaObject, lazyLoader, columnPrefix) || foundValues;
1 ✔
512
        putAncestor(rowValue, resultMapId);
1 ✔
513
        foundValues = applyNestedResultMappings(rsw, resultMap, metaObject, columnPrefix, combinedKey, true)
1 ✔
514
            || foundValues;
515
        ancestorObjects.remove(resultMapId);
1 ✔
516
        foundValues = lazyLoader.size() > 0 || foundValues;
1 ✔
517
        rowValue = foundValues || configuration.isReturnInstanceForEmptyRow() ? rowValue : null;
1 ✔
518
      }
519
      if (combinedKey != CacheKey.NULL_CACHE_KEY) {
1 ✔
520
        nestedResultObjects.put(combinedKey, rowValue);
1 ✔
521
      }
522
    }
523
    return rowValue;
1 ✔
524
  }
525

526
  private void putAncestor(Object resultObject, String resultMapId) {
527
    ancestorObjects.put(resultMapId, resultObject);
1 ✔
528
  }
1 ✔
529

530
  private boolean shouldApplyAutomaticMappings(ResultMap resultMap, boolean isNested) {
531
    if (resultMap.getAutoMapping() != null) {
1 ✔
532
      return resultMap.getAutoMapping();
1 ✔
533
    }
534
    if (isNested) {
1 ✔
535
      return AutoMappingBehavior.FULL == configuration.getAutoMappingBehavior();
1 ✔
536
    } else {
537
      return AutoMappingBehavior.NONE != configuration.getAutoMappingBehavior();
1 ✔
538
    }
539
  }
540

541
  //
542
  // PROPERTY MAPPINGS
543
  //
544

545
  private boolean applyPropertyMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject,
546
      ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException {
547
    final Set<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix);
1 ✔
548
    boolean foundValues = false;
1 ✔
549
    final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings();
1 ✔
550
    for (ResultMapping propertyMapping : propertyMappings) {
1 ✔
551
      String column = prependPrefix(propertyMapping.getColumn(), columnPrefix);
1 ✔
552
      if (propertyMapping.getNestedResultMapId() != null && !JdbcType.CURSOR.equals(propertyMapping.getJdbcType())) {
1 !
553
        // the user added a column attribute to a nested result map, ignore it
554
        column = null;
1 ✔
555
      }
556
      if (propertyMapping.isCompositeResult()
1 ✔
557
          || column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH))
1 ✔
558
          || propertyMapping.getResultSet() != null) {
1 ✔
559
        Object value = getPropertyMappingValue(rsw, metaObject, propertyMapping, lazyLoader, columnPrefix);
1 ✔
560
        // issue #541 make property optional
561
        final String property = propertyMapping.getProperty();
1 ✔
562
        if (property == null) {
1 ✔
563
          continue;
1 ✔
564
        }
565
        if (value == DEFERRED) {
1 ✔
566
          foundValues = true;
1 ✔
567
          continue;
1 ✔
568
        }
569
        if (value != null) {
1 ✔
570
          foundValues = true;
1 ✔
571
        }
572
        if (value != null
1 ✔
573
            || configuration.isCallSettersOnNulls() && !metaObject.getSetterType(property).isPrimitive()) {
1 !
574
          // gcode issue #377, call setter on nulls (value is not 'found')
575
          metaObject.setValue(property, value);
1 ✔
576
        }
577
      }
578
    }
1 ✔
579
    return foundValues;
1 ✔
580
  }
581

582
  private Object getPropertyMappingValue(ResultSetWrapper rsw, MetaObject metaResultObject,
583
      ResultMapping propertyMapping, ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException {
584
    final ResultSet rs = rsw.getResultSet();
1 ✔
585
    if (propertyMapping.getNestedQueryId() != null) {
1 ✔
586
      return getNestedQueryMappingValue(rsw, metaResultObject, propertyMapping, lazyLoader, columnPrefix);
1 ✔
587
    }
588
    if (JdbcType.CURSOR.equals(propertyMapping.getJdbcType())) {
1 !
589
      List<Object> results = getNestedCursorValue(rsw, propertyMapping, columnPrefix);
×
590
      linkObjects(metaResultObject, propertyMapping, results.get(0), true);
×
591
      return metaResultObject.getValue(propertyMapping.getProperty());
×
592
    }
593
    if (propertyMapping.getResultSet() != null) {
1 ✔
594
      addPendingChildRelation(rs, metaResultObject, propertyMapping); // TODO is that OK?
1 ✔
595
      return DEFERRED;
1 ✔
596
    } else {
597
      final String column = prependPrefix(propertyMapping.getColumn(), columnPrefix);
1 ✔
598
      TypeHandler<?> typeHandler = propertyMapping.getTypeHandler();
1 ✔
599
      if (typeHandler == null) {
1 ✔
600
        final String property = propertyMapping.getProperty();
1 ✔
601
        Type javaType = property == null ? null : metaResultObject.getGenericSetterType(property).getKey();
1 ✔
602
        if (Object.class == javaType) {
1 ✔
603
          // Use user-specified javaType if exists
604
          javaType = propertyMapping.getJavaType();
1 ✔
605
        }
606
        typeHandler = rsw.getTypeHandler(javaType, column);
1 ✔
607
        if (typeHandler == null) {
1 ✔
608
          throw new ExecutorException(
1 ✔
609
              "No type handler found for '" + javaType + "' and JDBC type '" + rsw.getJdbcType(column) + "'");
1 ✔
610
        }
611
      }
612
      return typeHandler.getResult(rs, column);
1 ✔
613
    }
614
  }
615

616
  private List<Object> getNestedCursorValue(ResultSetWrapper rsw, ResultMapping propertyMapping,
617
      String parentColumnPrefix) throws SQLException {
618
    final String column = prependPrefix(propertyMapping.getColumn(), parentColumnPrefix);
×
UNCOV
619
    ResultMap nestedResultMap = resolveDiscriminatedResultMap(rsw,
×
620
        configuration.getResultMap(propertyMapping.getNestedResultMapId()),
×
621
        getColumnPrefix(parentColumnPrefix, propertyMapping));
×
622
    ResultSetWrapper nestedRsw = new ResultSetWrapper(rsw.getResultSet().getObject(column, ResultSet.class),
×
623
        configuration);
UNCOV
624
    List<Object> results = new ArrayList<>();
×
UNCOV
625
    handleResultSet(nestedRsw, nestedResultMap, results, null);
×
UNCOV
626
    return results;
×
627
  }
628

629
  private List<UnMappedColumnAutoMapping> createAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap,
630
      MetaObject metaObject, String columnPrefix) throws SQLException {
631
    final String mapKey = resultMap.getId() + ":" + columnPrefix;
1 ✔
632
    List<UnMappedColumnAutoMapping> autoMapping = autoMappingsCache.get(mapKey);
1 ✔
633
    if (autoMapping == null) {
1 ✔
634
      autoMapping = new ArrayList<>();
1 ✔
635
      final List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
1 ✔
636
      // Remove the entry to release the memory
637
      List<String> mappedInConstructorAutoMapping = constructorAutoMappingColumns.remove(mapKey);
1 ✔
638
      if (mappedInConstructorAutoMapping != null) {
1 ✔
639
        unmappedColumnNames.removeAll(mappedInConstructorAutoMapping);
1 ✔
640
      }
641
      for (String columnName : unmappedColumnNames) {
1 ✔
642
        String propertyName = columnName;
1 ✔
643
        if (columnPrefix != null && !columnPrefix.isEmpty()) {
1 !
644
          // When columnPrefix is specified,
645
          // ignore columns without the prefix.
646
          if (!columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
1 ✔
647
            continue;
1 ✔
648
          }
649
          propertyName = columnName.substring(columnPrefix.length());
1 ✔
650
        }
651
        final String property = metaObject.findProperty(propertyName, configuration.isMapUnderscoreToCamelCase());
1 ✔
652
        if (property != null && metaObject.hasSetter(property)) {
1 ✔
653
          if (resultMap.getMappedProperties().contains(property)) {
1 ✔
654
            continue;
1 ✔
655
          }
656
          final Type propertyType = metaObject.getGenericSetterType(property).getKey();
1 ✔
657
          TypeHandler<?> typeHandler = rsw.getTypeHandler(propertyType, columnName);
1 ✔
658
          if (typeHandler != null) {
1 ✔
659
            autoMapping.add(new UnMappedColumnAutoMapping(columnName, property, typeHandler,
1 ✔
660
                propertyType instanceof Class && ((Class<?>) propertyType).isPrimitive()));
1 ✔
661
          } else {
662
            configuration.getAutoMappingUnknownColumnBehavior().doAction(mappedStatement, columnName, property,
1 ✔
663
                propertyType);
664
          }
665
        } else {
1 ✔
666
          configuration.getAutoMappingUnknownColumnBehavior().doAction(mappedStatement, columnName,
1 ✔
667
              property != null ? property : propertyName, null);
1 ✔
668
        }
669
      }
1 ✔
670
      autoMappingsCache.put(mapKey, autoMapping);
1 ✔
671
    }
672
    return autoMapping;
1 ✔
673
  }
674

675
  private boolean applyAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject,
676
      String columnPrefix) throws SQLException {
677
    List<UnMappedColumnAutoMapping> autoMapping = createAutomaticMappings(rsw, resultMap, metaObject, columnPrefix);
1 ✔
678
    boolean foundValues = false;
1 ✔
679
    if (!autoMapping.isEmpty()) {
1 ✔
680
      for (UnMappedColumnAutoMapping mapping : autoMapping) {
1 ✔
681
        final Object value = mapping.typeHandler.getResult(rsw.getResultSet(), mapping.column);
1 ✔
682
        if (value != null) {
1 ✔
683
          foundValues = true;
1 ✔
684
        }
685
        if (value != null || configuration.isCallSettersOnNulls() && !mapping.primitive) {
1 !
686
          // gcode issue #377, call setter on nulls (value is not 'found')
687
          metaObject.setValue(mapping.property, value);
1 ✔
688
        }
689
      }
1 ✔
690
    }
691
    return foundValues;
1 ✔
692
  }
693

694
  // MULTIPLE RESULT SETS
695

696
  private void linkToParents(ResultSet rs, ResultMapping parentMapping, Object rowValue) throws SQLException {
697
    CacheKey parentKey = createKeyForMultipleResults(rs, parentMapping, parentMapping.getColumn(),
1 ✔
698
        parentMapping.getForeignColumn());
1 ✔
699
    List<PendingRelation> parents = pendingRelations.get(parentKey);
1 ✔
700
    if (parents != null) {
1 ✔
701
      for (PendingRelation parent : parents) {
1 ✔
702
        if (parent != null && rowValue != null) {
1 !
703
          linkObjects(parent.metaObject, parent.propertyMapping, rowValue);
1 ✔
704
        }
705
      }
1 ✔
706
    }
707
  }
1 ✔
708

709
  private void addPendingChildRelation(ResultSet rs, MetaObject metaResultObject, ResultMapping parentMapping)
710
      throws SQLException {
711
    CacheKey cacheKey = createKeyForMultipleResults(rs, parentMapping, parentMapping.getColumn(),
1 ✔
712
        parentMapping.getColumn());
1 ✔
713
    PendingRelation deferLoad = new PendingRelation();
1 ✔
714
    deferLoad.metaObject = metaResultObject;
1 ✔
715
    deferLoad.propertyMapping = parentMapping;
1 ✔
716
    List<PendingRelation> relations = pendingRelations.computeIfAbsent(cacheKey, k -> new ArrayList<>());
1 ✔
717
    // issue #255
718
    relations.add(deferLoad);
1 ✔
719
    ResultMapping previous = nextResultMaps.get(parentMapping.getResultSet());
1 ✔
720
    if (previous == null) {
1 ✔
721
      nextResultMaps.put(parentMapping.getResultSet(), parentMapping);
1 ✔
722
    } else if (!previous.equals(parentMapping)) {
1 !
UNCOV
723
      throw new ExecutorException("Two different properties are mapped to the same resultSet");
×
724
    }
725
  }
1 ✔
726

727
  private CacheKey createKeyForMultipleResults(ResultSet rs, ResultMapping resultMapping, String names, String columns)
728
      throws SQLException {
729
    CacheKey cacheKey = new CacheKey();
1 ✔
730
    cacheKey.update(resultMapping);
1 ✔
731
    if (columns != null && names != null) {
1 !
732
      String[] columnsArray = columns.split(",");
1 ✔
733
      String[] namesArray = names.split(",");
1 ✔
734
      for (int i = 0; i < columnsArray.length; i++) {
1 ✔
735
        Object value = rs.getString(columnsArray[i]);
1 ✔
736
        if (value != null) {
1 !
737
          cacheKey.update(namesArray[i]);
1 ✔
738
          cacheKey.update(value);
1 ✔
739
        }
740
      }
741
    }
742
    return cacheKey;
1 ✔
743
  }
744

745
  //
746
  // INSTANTIATION & CONSTRUCTOR MAPPING
747
  //
748

749
  private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, ResultLoaderMap lazyLoader,
750
      String columnPrefix, CacheKey parentRowKey) throws SQLException {
751
    this.useConstructorMappings = false; // reset previous mapping result
1 ✔
752
    final List<Class<?>> constructorArgTypes = new ArrayList<>();
1 ✔
753
    final List<Object> constructorArgs = new ArrayList<>();
1 ✔
754

755
    Object resultObject = createResultObject(rsw, resultMap, constructorArgTypes, constructorArgs, columnPrefix,
1 ✔
756
        parentRowKey);
757
    if (resultObject != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
1 ✔
758
      final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings();
1 ✔
759
      for (ResultMapping propertyMapping : propertyMappings) {
1 ✔
760
        // issue gcode #109 && issue #149
761
        if (propertyMapping.getNestedQueryId() != null && propertyMapping.isLazy()) {
1 ✔
762
          resultObject = configuration.getProxyFactory().createProxy(resultObject, lazyLoader, configuration,
1 ✔
763
              objectFactory, constructorArgTypes, constructorArgs);
764
          break;
1 ✔
765
        }
766
      }
1 ✔
767

768
      // (issue #101)
769
      if (resultMap.hasResultMapsUsingConstructorCollection() && resultObject instanceof PendingConstructorCreation) {
1 !
770
        linkNestedPendingCreations(rsw, resultMap, columnPrefix, parentRowKey,
1 ✔
771
            (PendingConstructorCreation) resultObject, constructorArgs);
772
      }
773
    }
774

775
    this.useConstructorMappings = resultObject != null && !constructorArgTypes.isEmpty(); // set current mapping result
1 ✔
776
    return resultObject;
1 ✔
777
  }
778

779
  private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, List<Class<?>> constructorArgTypes,
780
      List<Object> constructorArgs, String columnPrefix, CacheKey parentRowKey) throws SQLException {
781

782
    final Class<?> resultType = resultMap.getType();
1 ✔
783
    final MetaClass metaType = MetaClass.forClass(resultType, reflectorFactory);
1 ✔
784
    final List<ResultMapping> constructorMappings = resultMap.getConstructorResultMappings();
1 ✔
785
    if (hasTypeHandlerForResultObject(rsw, resultType)) {
1 ✔
786
      return createPrimitiveResultObject(rsw, resultMap, columnPrefix);
1 ✔
787
    }
788
    if (!constructorMappings.isEmpty()) {
1 ✔
789
      return createParameterizedResultObject(rsw, resultType, constructorMappings, constructorArgTypes, constructorArgs,
1 ✔
790
          columnPrefix, resultMap.hasResultMapsUsingConstructorCollection(), parentRowKey);
1 ✔
791
    } else if (resultType.isInterface() || metaType.hasDefaultConstructor()) {
1 ✔
792
      return objectFactory.create(resultType);
1 ✔
793
    } else if (shouldApplyAutomaticMappings(resultMap, false)) {
1 !
794
      return createByConstructorSignature(rsw, resultMap, columnPrefix, resultType, constructorArgTypes,
1 ✔
795
          constructorArgs);
796
    }
UNCOV
797
    throw new ExecutorException("Do not know how to create an instance of " + resultType);
×
798
  }
799

800
  Object createParameterizedResultObject(ResultSetWrapper rsw, Class<?> resultType,
801
      List<ResultMapping> constructorMappings, List<Class<?>> constructorArgTypes, List<Object> constructorArgs,
802
      String columnPrefix, boolean useCollectionConstructorInjection, CacheKey parentRowKey) {
803
    boolean foundValues = false;
1 ✔
804

805
    for (ResultMapping constructorMapping : constructorMappings) {
1 ✔
806
      final Class<?> parameterType = constructorMapping.getJavaType();
1 ✔
807
      final String column = constructorMapping.getColumn();
1 ✔
808
      final Object value;
809
      try {
810
        if (constructorMapping.getNestedQueryId() != null) {
1 ✔
811
          value = getNestedQueryConstructorValue(rsw, constructorMapping, columnPrefix);
1 ✔
812
        } else if (JdbcType.CURSOR.equals(constructorMapping.getJdbcType())) {
1 !
813
          List<?> result = (List<?>) getNestedCursorValue(rsw, constructorMapping, columnPrefix).get(0);
×
814
          if (objectFactory.isCollection(parameterType)) {
×
815
            MetaObject collection = configuration.newMetaObject(objectFactory.create(parameterType));
×
UNCOV
816
            collection.addAll((List<?>) result);
×
UNCOV
817
            value = collection.getOriginalObject();
×
UNCOV
818
          } else {
×
UNCOV
819
            value = toSingleObj(result);
×
820
          }
821
        } else if (constructorMapping.getNestedResultMapId() != null) {
1 ✔
822
          final String constructorColumnPrefix = getColumnPrefix(columnPrefix, constructorMapping);
1 ✔
823
          final ResultMap resultMap = resolveDiscriminatedResultMap(rsw,
1 ✔
824
              configuration.getResultMap(constructorMapping.getNestedResultMapId()), constructorColumnPrefix);
1 ✔
825
          value = getRowValue(rsw, resultMap, constructorColumnPrefix,
1 ✔
826
              useCollectionConstructorInjection ? parentRowKey : null);
1 ✔
827
        } else {
1 ✔
828
          TypeHandler<?> typeHandler = constructorMapping.getTypeHandler();
1 ✔
829
          if (typeHandler == null) {
1 ✔
830
            typeHandler = typeHandlerRegistry.getTypeHandler(constructorMapping.getJavaType(), rsw.getJdbcType(column));
1 ✔
831
          }
832
          value = typeHandler.getResult(rsw.getResultSet(), prependPrefix(column, columnPrefix));
1 ✔
833
        }
834
      } catch (ResultMapException | SQLException e) {
1 ✔
835
        throw new ExecutorException("Could not process result for mapping: " + constructorMapping, e);
1 ✔
836
      }
1 ✔
837

838
      constructorArgTypes.add(parameterType);
1 ✔
839
      constructorArgs.add(value);
1 ✔
840

841
      foundValues = value != null || foundValues;
1 ✔
842
    }
1 ✔
843

844
    if (!foundValues) {
1 ✔
845
      return null;
1 ✔
846
    }
847

848
    if (useCollectionConstructorInjection) {
1 ✔
849
      // at least one of the nestedResultMaps contained a collection, we have to defer until later
850
      return new PendingConstructorCreation(resultType, constructorArgTypes, constructorArgs);
1 ✔
851
    }
852

853
    return objectFactory.create(resultType, constructorArgTypes, constructorArgs);
1 ✔
854
  }
855

856
  private Object createByConstructorSignature(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix,
857
      Class<?> resultType, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) throws SQLException {
858
    return applyConstructorAutomapping(rsw, resultMap, columnPrefix, resultType, constructorArgTypes, constructorArgs,
1 ✔
859
        findConstructorForAutomapping(resultType, rsw).orElseThrow(() -> new ExecutorException(
1 ✔
UNCOV
860
            "No constructor found in " + resultType.getName() + " matching " + rsw.getClassNames())));
×
861
  }
862

863
  private Optional<Constructor<?>> findConstructorForAutomapping(final Class<?> resultType, ResultSetWrapper rsw) {
864
    Constructor<?>[] constructors = resultType.getDeclaredConstructors();
1 ✔
865
    if (constructors.length == 1) {
1 ✔
866
      return Optional.of(constructors[0]);
1 ✔
867
    }
868
    Optional<Constructor<?>> annotated = Arrays.stream(constructors)
1 ✔
869
        .filter(x -> x.isAnnotationPresent(AutomapConstructor.class)).reduce((x, y) -> {
1 ✔
870
          throw new ExecutorException("@AutomapConstructor should be used in only one constructor.");
1 ✔
871
        });
872
    if (annotated.isPresent()) {
1 ✔
873
      return annotated;
1 ✔
874
    }
875
    if (configuration.isArgNameBasedConstructorAutoMapping()) {
1 !
876
      // Finding-best-match type implementation is possible,
877
      // but using @AutomapConstructor seems sufficient.
UNCOV
878
      throw new ExecutorException(MessageFormat.format(
×
879
          "'argNameBasedConstructorAutoMapping' is enabled and the class ''{0}'' has multiple constructors, so @AutomapConstructor must be added to one of the constructors.",
UNCOV
880
          resultType.getName()));
×
881
    } else {
882
      return Arrays.stream(constructors).filter(x -> findUsableConstructorByArgTypes(x, rsw.getJdbcTypes())).findAny();
1 ✔
883
    }
884
  }
885

886
  private boolean findUsableConstructorByArgTypes(final Constructor<?> constructor, final List<JdbcType> jdbcTypes) {
887
    final Class<?>[] parameterTypes = constructor.getParameterTypes();
1 ✔
888
    if (parameterTypes.length != jdbcTypes.size()) {
1 ✔
889
      return false;
1 ✔
890
    }
891
    for (int i = 0; i < parameterTypes.length; i++) {
1 ✔
892
      if (!typeHandlerRegistry.hasTypeHandler(parameterTypes[i], jdbcTypes.get(i))) {
1 !
UNCOV
893
        return false;
×
894
      }
895
    }
896
    return true;
1 ✔
897
  }
898

899
  private Object applyConstructorAutomapping(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix,
900
      Class<?> resultType, List<Class<?>> constructorArgTypes, List<Object> constructorArgs, Constructor<?> constructor)
901
      throws SQLException {
902
    boolean foundValues = false;
1 ✔
903
    if (configuration.isArgNameBasedConstructorAutoMapping()) {
1 ✔
904
      foundValues = applyArgNameBasedConstructorAutoMapping(rsw, resultMap, columnPrefix, constructorArgTypes,
1 ✔
905
          constructorArgs, constructor, foundValues);
906
    } else {
907
      foundValues = applyColumnOrderBasedConstructorAutomapping(rsw, constructorArgTypes, constructorArgs, constructor,
1 ✔
908
          foundValues);
909
    }
910
    return foundValues || configuration.isReturnInstanceForEmptyRow()
1 !
911
        ? objectFactory.create(resultType, constructorArgTypes, constructorArgs) : null;
1 ✔
912
  }
913

914
  private boolean applyColumnOrderBasedConstructorAutomapping(ResultSetWrapper rsw, List<Class<?>> constructorArgTypes,
915
      List<Object> constructorArgs, Constructor<?> constructor, boolean foundValues) throws SQLException {
916
    Class<?>[] parameterTypes = constructor.getParameterTypes();
1 ✔
917

918
    if (parameterTypes.length > rsw.getClassNames().size()) {
1 ✔
919
      throw new ExecutorException(MessageFormat.format(
1 ✔
920
          "Constructor auto-mapping of ''{0}'' failed. The constructor takes ''{1}'' arguments, but there are only ''{2}'' columns in the result set.",
921
          constructor, parameterTypes.length, rsw.getClassNames().size()));
1 ✔
922
    }
923

924
    for (int i = 0; i < parameterTypes.length; i++) {
1 ✔
925
      Class<?> parameterType = parameterTypes[i];
1 ✔
926
      String columnName = rsw.getColumnNames().get(i);
1 ✔
927
      TypeHandler<?> typeHandler = rsw.getTypeHandler(parameterType, columnName);
1 ✔
928
      Object value = typeHandler.getResult(rsw.getResultSet(), columnName);
1 ✔
929
      constructorArgTypes.add(parameterType);
1 ✔
930
      constructorArgs.add(value);
1 ✔
931
      foundValues = value != null || foundValues;
1 !
932
    }
933
    return foundValues;
1 ✔
934
  }
935

936
  private boolean applyArgNameBasedConstructorAutoMapping(ResultSetWrapper rsw, ResultMap resultMap,
937
      String columnPrefix, List<Class<?>> constructorArgTypes, List<Object> constructorArgs, Constructor<?> constructor,
938
      boolean foundValues) throws SQLException {
939
    List<String> missingArgs = null;
1 ✔
940
    Parameter[] params = constructor.getParameters();
1 ✔
941
    for (Parameter param : params) {
1 ✔
942
      boolean columnNotFound = true;
1 ✔
943
      Param paramAnno = param.getAnnotation(Param.class);
1 ✔
944
      String paramName = paramAnno == null ? param.getName() : paramAnno.value();
1 ✔
945
      for (String columnName : rsw.getColumnNames()) {
1 ✔
946
        if (columnMatchesParam(columnName, paramName, columnPrefix)) {
1 ✔
947
          Class<?> paramType = param.getType();
1 ✔
948
          TypeHandler<?> typeHandler = rsw.getTypeHandler(paramType, columnName);
1 ✔
949
          Object value = typeHandler.getResult(rsw.getResultSet(), columnName);
1 ✔
950
          constructorArgTypes.add(paramType);
1 ✔
951
          constructorArgs.add(value);
1 ✔
952
          final String mapKey = resultMap.getId() + ":" + columnPrefix;
1 ✔
953
          if (!autoMappingsCache.containsKey(mapKey)) {
1 !
954
            constructorAutoMappingColumns.computeIfAbsent(mapKey, k -> new ArrayList<>()).add(columnName);
1 ✔
955
          }
956
          columnNotFound = false;
1 ✔
957
          foundValues = value != null || foundValues;
1 !
958
        }
959
      }
1 ✔
960
      if (columnNotFound) {
1 ✔
961
        if (missingArgs == null) {
1 !
962
          missingArgs = new ArrayList<>();
1 ✔
963
        }
964
        missingArgs.add(paramName);
1 ✔
965
      }
966
    }
967
    if (foundValues && constructorArgs.size() < params.length) {
1 ✔
968
      throw new ExecutorException(MessageFormat.format(
1 ✔
969
          "Constructor auto-mapping of ''{1}'' failed " + "because ''{0}'' were not found in the result set; "
970
              + "Available columns are ''{2}'' and mapUnderscoreToCamelCase is ''{3}''.",
971
          missingArgs, constructor, rsw.getColumnNames(), configuration.isMapUnderscoreToCamelCase()));
1 ✔
972
    }
973
    return foundValues;
1 ✔
974
  }
975

976
  private boolean columnMatchesParam(String columnName, String paramName, String columnPrefix) {
977
    if (columnPrefix != null) {
1 ✔
978
      if (!columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
1 ✔
979
        return false;
1 ✔
980
      }
981
      columnName = columnName.substring(columnPrefix.length());
1 ✔
982
    }
983
    return paramName
1 ✔
984
        .equalsIgnoreCase(configuration.isMapUnderscoreToCamelCase() ? columnName.replace("_", "") : columnName);
1 ✔
985
  }
986

987
  private Object createPrimitiveResultObject(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix)
988
      throws SQLException {
989
    final Class<?> resultType = resultMap.getType();
1 ✔
990
    final String columnName;
991
    if (!resultMap.getResultMappings().isEmpty()) {
1 ✔
992
      final List<ResultMapping> resultMappingList = resultMap.getResultMappings();
1 ✔
993
      final ResultMapping mapping = resultMappingList.get(0);
1 ✔
994
      columnName = prependPrefix(mapping.getColumn(), columnPrefix);
1 ✔
995
    } else {
1 ✔
996
      columnName = rsw.getColumnNames().get(0);
1 ✔
997
    }
998
    final TypeHandler<?> typeHandler = rsw.getTypeHandler(resultType, columnName);
1 ✔
999
    return typeHandler.getResult(rsw.getResultSet(), columnName);
1 ✔
1000
  }
1001

1002
  //
1003
  // NESTED QUERY
1004
  //
1005

1006
  private Object getNestedQueryConstructorValue(ResultSetWrapper rsw, ResultMapping constructorMapping,
1007
      String columnPrefix) throws SQLException {
1008
    final String nestedQueryId = constructorMapping.getNestedQueryId();
1 ✔
1009
    final MappedStatement nestedQuery = configuration.getMappedStatement(nestedQueryId);
1 ✔
1010
    final Class<?> nestedQueryParameterType = nestedQuery.getParameterMap().getType();
1 ✔
1011
    final Object nestedQueryParameterObject = prepareParameterForNestedQuery(rsw, constructorMapping,
1 ✔
1012
        nestedQueryParameterType, columnPrefix);
1013
    Object value = null;
1 ✔
1014
    if (nestedQueryParameterObject != null) {
1 !
1015
      final BoundSql nestedBoundSql = nestedQuery.getBoundSql(nestedQueryParameterObject);
1 ✔
1016
      final CacheKey key = executor.createCacheKey(nestedQuery, nestedQueryParameterObject, RowBounds.DEFAULT,
1 ✔
1017
          nestedBoundSql);
1018
      final Class<?> targetType = constructorMapping.getJavaType();
1 ✔
1019
      final ResultLoader resultLoader = new ResultLoader(configuration, executor, nestedQuery,
1 ✔
1020
          nestedQueryParameterObject, targetType, key, nestedBoundSql);
1021
      value = resultLoader.loadResult();
1 ✔
1022
    }
1023
    return value;
1 ✔
1024
  }
1025

1026
  private Object getNestedQueryMappingValue(ResultSetWrapper rsw, MetaObject metaResultObject,
1027
      ResultMapping propertyMapping, ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException {
1028
    final String nestedQueryId = propertyMapping.getNestedQueryId();
1 ✔
1029
    final String property = propertyMapping.getProperty();
1 ✔
1030
    final MappedStatement nestedQuery = configuration.getMappedStatement(nestedQueryId);
1 ✔
1031
    final Class<?> nestedQueryParameterType = nestedQuery.getParameterMap().getType();
1 ✔
1032
    final Object nestedQueryParameterObject = prepareParameterForNestedQuery(rsw, propertyMapping,
1 ✔
1033
        nestedQueryParameterType, columnPrefix);
1034
    Object value = null;
1 ✔
1035
    if (nestedQueryParameterObject != null) {
1 ✔
1036
      final BoundSql nestedBoundSql = nestedQuery.getBoundSql(nestedQueryParameterObject);
1 ✔
1037
      final CacheKey key = executor.createCacheKey(nestedQuery, nestedQueryParameterObject, RowBounds.DEFAULT,
1 ✔
1038
          nestedBoundSql);
1039
      final Class<?> targetType = propertyMapping.getJavaType();
1 ✔
1040
      if (executor.isCached(nestedQuery, key)) {
1 ✔
1041
        executor.deferLoad(nestedQuery, metaResultObject, property, key, targetType);
1 ✔
1042
        value = DEFERRED;
1 ✔
1043
      } else {
1044
        final ResultLoader resultLoader = new ResultLoader(configuration, executor, nestedQuery,
1 ✔
1045
            nestedQueryParameterObject, targetType, key, nestedBoundSql);
1046
        if (propertyMapping.isLazy()) {
1 ✔
1047
          lazyLoader.addLoader(property, metaResultObject, resultLoader);
1 ✔
1048
          value = DEFERRED;
1 ✔
1049
        } else {
1050
          value = resultLoader.loadResult();
1 ✔
1051
        }
1052
      }
1053
    }
1054
    return value;
1 ✔
1055
  }
1056

1057
  private Object prepareParameterForNestedQuery(ResultSetWrapper rsw, ResultMapping resultMapping,
1058
      Class<?> parameterType, String columnPrefix) throws SQLException {
1059
    if (resultMapping.isCompositeResult()) {
1 ✔
1060
      return prepareCompositeKeyParameter(rsw, resultMapping, parameterType, columnPrefix);
1 ✔
1061
    }
1062
    return prepareSimpleKeyParameter(rsw, resultMapping, parameterType, columnPrefix);
1 ✔
1063
  }
1064

1065
  private Object prepareSimpleKeyParameter(ResultSetWrapper rsw, ResultMapping resultMapping, Class<?> parameterType,
1066
      String columnPrefix) throws SQLException {
1067
    // parameterType is ignored in this case
1068
    final String columnName = prependPrefix(resultMapping.getColumn(), columnPrefix);
1 ✔
1069
    final TypeHandler<?> typeHandler = rsw.getTypeHandler(null, columnName);
1 ✔
1070
    return typeHandler.getResult(rsw.getResultSet(), columnName);
1 ✔
1071
  }
1072

1073
  private Object prepareCompositeKeyParameter(ResultSetWrapper rsw, ResultMapping resultMapping, Class<?> parameterType,
1074
      String columnPrefix) throws SQLException {
1075
    // Map is used if parameterType is not specified
1076
    final Object parameterObject = instantiateParameterObject(parameterType);
1 ✔
1077
    final MetaObject metaObject = configuration.newMetaObject(parameterObject);
1 ✔
1078
    boolean foundValues = false;
1 ✔
1079
    for (ResultMapping innerResultMapping : resultMapping.getComposites()) {
1 ✔
1080
      final String columnName = prependPrefix(innerResultMapping.getColumn(), columnPrefix);
1 ✔
1081
      final TypeHandler<?> typeHandler = rsw
1 ✔
1082
          .getTypeHandler(metaObject.getGenericSetterType(innerResultMapping.getProperty()).getKey(), columnName);
1 ✔
1083
      final Object propValue = typeHandler.getResult(rsw.getResultSet(), columnName);
1 ✔
1084
      // issue #353 & #560 do not execute nested query if key is null
1085
      if (propValue != null) {
1 ✔
1086
        metaObject.setValue(innerResultMapping.getProperty(), propValue);
1 ✔
1087
        foundValues = true;
1 ✔
1088
      }
1089
    }
1 ✔
1090
    return foundValues ? parameterObject : null;
1 ✔
1091
  }
1092

1093
  private Object instantiateParameterObject(Class<?> parameterType) {
1094
    if (parameterType == null) {
1 ✔
1095
      return new HashMap<>();
1 ✔
1096
    }
1097
    if (ParamMap.class.equals(parameterType)) {
1 ✔
1098
      return new HashMap<>(); // issue #649
1 ✔
1099
    } else {
1100
      return objectFactory.create(parameterType);
1 ✔
1101
    }
1102
  }
1103

1104
  //
1105
  // DISCRIMINATOR
1106
  //
1107

1108
  public ResultMap resolveDiscriminatedResultMap(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix)
1109
      throws SQLException {
1110
    Set<String> pastDiscriminators = new HashSet<>();
1 ✔
1111
    Discriminator discriminator = resultMap.getDiscriminator();
1 ✔
1112
    while (discriminator != null) {
1 ✔
1113
      final Object value = getDiscriminatorValue(rsw, discriminator, columnPrefix);
1 ✔
1114
      final String discriminatedMapId = discriminator.getMapIdFor(String.valueOf(value));
1 ✔
1115
      if (!configuration.hasResultMap(discriminatedMapId)) {
1 ✔
1116
        break;
1 ✔
1117
      }
1118
      resultMap = configuration.getResultMap(discriminatedMapId);
1 ✔
1119
      Discriminator lastDiscriminator = discriminator;
1 ✔
1120
      discriminator = resultMap.getDiscriminator();
1 ✔
1121
      if (discriminator == lastDiscriminator || !pastDiscriminators.add(discriminatedMapId)) {
1 !
1122
        break;
1 ✔
1123
      }
1124
    }
1 ✔
1125
    return resultMap;
1 ✔
1126
  }
1127

1128
  private Object getDiscriminatorValue(ResultSetWrapper rsw, Discriminator discriminator, String columnPrefix)
1129
      throws SQLException {
1130
    final ResultMapping resultMapping = discriminator.getResultMapping();
1 ✔
1131
    String column = prependPrefix(resultMapping.getColumn(), columnPrefix);
1 ✔
1132
    TypeHandler<?> typeHandler = resultMapping.getTypeHandler();
1 ✔
1133
    if (typeHandler == null) {
1 ✔
1134
      typeHandler = typeHandlerRegistry.getTypeHandler(resultMapping.getJavaType(), rsw.getJdbcType(column));
1 ✔
1135
    }
1136
    return typeHandler.getResult(rsw.getResultSet(), column);
1 ✔
1137
  }
1138

1139
  private String prependPrefix(String columnName, String prefix) {
1140
    if (columnName == null || columnName.length() == 0 || prefix == null || prefix.length() == 0) {
1 !
1141
      return columnName;
1 ✔
1142
    }
1143
    return prefix + columnName;
1 ✔
1144
  }
1145

1146
  //
1147
  // HANDLE NESTED RESULT MAPS
1148
  //
1149

1150
  private void handleRowValuesForNestedResultMap(ResultSetWrapper rsw, ResultMap resultMap,
1151
      ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
1152
    final boolean useCollectionConstructorInjection = resultMap.hasResultMapsUsingConstructorCollection();
1 ✔
1153
    PendingConstructorCreation lastHandledCreation = null;
1 ✔
1154
    if (useCollectionConstructorInjection) {
1 ✔
1155
      verifyPendingCreationPreconditions(parentMapping);
1 ✔
1156
    }
1157

1158
    final DefaultResultContext<Object> resultContext = new DefaultResultContext<>();
1 ✔
1159
    ResultSet resultSet = rsw.getResultSet();
1 ✔
1160
    skipRows(resultSet, rowBounds);
1 ✔
1161
    Object rowValue = previousRowValue;
1 ✔
1162

1163
    while (shouldProcessMoreRows(resultContext, rowBounds) && !resultSet.isClosed() && resultSet.next()) {
1 ✔
1164
      final ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rsw, resultMap, null);
1 ✔
1165
      final CacheKey rowKey = createRowKey(discriminatedResultMap, rsw, null);
1 ✔
1166

1167
      final Object partialObject = nestedResultObjects.get(rowKey);
1 ✔
1168
      final boolean foundNewUniqueRow = partialObject == null;
1 ✔
1169

1170
      // issue #577, #542 && #101
1171
      if (useCollectionConstructorInjection) {
1 ✔
1172
        if (foundNewUniqueRow && lastHandledCreation != null) {
1 ✔
1173
          createAndStorePendingCreation(resultHandler, resultSet, resultContext, lastHandledCreation);
1 ✔
1174
          lastHandledCreation = null;
1 ✔
1175
        }
1176

1177
        rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, null, partialObject);
1 ✔
1178
        if (rowValue instanceof PendingConstructorCreation) {
1 !
1179
          lastHandledCreation = (PendingConstructorCreation) rowValue;
1 ✔
1180
        }
1181
      } else if (mappedStatement.isResultOrdered()) {
1 ✔
1182
        if (foundNewUniqueRow && rowValue != null) {
1 ✔
1183
          nestedResultObjects.clear();
1 ✔
1184
          storeObject(resultHandler, resultContext, rowValue, parentMapping, resultSet);
1 ✔
1185
        }
1186
        rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, null, partialObject);
1 ✔
1187
      } else {
1188
        rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, null, partialObject);
1 ✔
1189
        if (foundNewUniqueRow) {
1 ✔
1190
          storeObject(resultHandler, resultContext, rowValue, parentMapping, resultSet);
1 ✔
1191
        }
1192
      }
1193
    }
1 ✔
1194

1195
    if (useCollectionConstructorInjection && lastHandledCreation != null) {
1 !
1196
      createAndStorePendingCreation(resultHandler, resultSet, resultContext, lastHandledCreation);
1 ✔
1197
    } else if (rowValue != null && mappedStatement.isResultOrdered()
1 ✔
1198
        && shouldProcessMoreRows(resultContext, rowBounds)) {
1 ✔
1199
      storeObject(resultHandler, resultContext, rowValue, parentMapping, resultSet);
1 ✔
1200
      previousRowValue = null;
1 ✔
1201
    } else if (rowValue != null) {
1 ✔
1202
      previousRowValue = rowValue;
1 ✔
1203
    }
1204
  }
1 ✔
1205

1206
  //
1207
  // NESTED RESULT MAP (PENDING CONSTRUCTOR CREATIONS)
1208
  //
1209
  private void linkNestedPendingCreations(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix,
1210
      CacheKey parentRowKey, PendingConstructorCreation pendingCreation, List<Object> constructorArgs)
1211
      throws SQLException {
1212
    if (parentRowKey == null) {
1 !
1213
      // nothing to link, possibly due to simple (non-nested) result map
UNCOV
1214
      return;
×
1215
    }
1216

1217
    final CacheKey rowKey = createRowKey(resultMap, rsw, columnPrefix);
1 ✔
1218
    final CacheKey combinedKey = combineKeys(rowKey, parentRowKey);
1 ✔
1219

1220
    if (combinedKey != CacheKey.NULL_CACHE_KEY) {
1 !
1221
      nestedResultObjects.put(combinedKey, pendingCreation);
1 ✔
1222
    }
1223

1224
    final List<ResultMapping> constructorMappings = resultMap.getConstructorResultMappings();
1 ✔
1225
    for (int index = 0; index < constructorMappings.size(); index++) {
1 ✔
1226
      final ResultMapping constructorMapping = constructorMappings.get(index);
1 ✔
1227
      final String nestedResultMapId = constructorMapping.getNestedResultMapId();
1 ✔
1228

1229
      if (nestedResultMapId == null) {
1 ✔
1230
        continue;
1 ✔
1231
      }
1232

1233
      final Class<?> javaType = constructorMapping.getJavaType();
1 ✔
1234
      if (javaType == null || !objectFactory.isCollection(javaType)) {
1 !
1235
        continue;
1 ✔
1236
      }
1237

1238
      final String constructorColumnPrefix = getColumnPrefix(columnPrefix, constructorMapping);
1 ✔
1239
      final ResultMap nestedResultMap = resolveDiscriminatedResultMap(rsw,
1 ✔
1240
          configuration.getResultMap(constructorMapping.getNestedResultMapId()), constructorColumnPrefix);
1 ✔
1241

1242
      final Object actualValue = constructorArgs.get(index);
1 ✔
1243
      final boolean hasValue = actualValue != null;
1 ✔
1244
      final boolean isInnerCreation = actualValue instanceof PendingConstructorCreation;
1 ✔
1245
      final boolean alreadyCreatedCollection = hasValue && objectFactory.isCollection(actualValue.getClass());
1 !
1246

1247
      if (!isInnerCreation) {
1 ✔
1248
        final Collection<Object> value = pendingCreation.initializeCollectionForResultMapping(objectFactory,
1 ✔
1249
            nestedResultMap, constructorMapping, index);
1 ✔
1250
        if (!alreadyCreatedCollection) {
1 !
1251
          // override values with empty collection
1252
          constructorArgs.set(index, value);
1 ✔
1253
        }
1254

1255
        // since we are linking a new value, we need to let nested objects know we did that
1256
        final CacheKey nestedRowKey = createRowKey(nestedResultMap, rsw, constructorColumnPrefix);
1 ✔
1257
        final CacheKey nestedCombinedKey = combineKeys(nestedRowKey, combinedKey);
1 ✔
1258

1259
        if (nestedCombinedKey != CacheKey.NULL_CACHE_KEY) {
1 ✔
1260
          nestedResultObjects.put(nestedCombinedKey, pendingCreation);
1 ✔
1261
        }
1262

1263
        if (hasValue) {
1 ✔
1264
          pendingCreation.linkCollectionValue(constructorMapping, actualValue);
1 ✔
1265
        }
1266
      } else {
1 ✔
1267
        final PendingConstructorCreation innerCreation = (PendingConstructorCreation) actualValue;
1 ✔
1268
        final Collection<Object> value = pendingCreation.initializeCollectionForResultMapping(objectFactory,
1 ✔
1269
            nestedResultMap, constructorMapping, index);
1 ✔
1270
        // we will fill this collection when building the final object
1271
        constructorArgs.set(index, value);
1 ✔
1272
        // link the creation for building later
1273
        pendingCreation.linkCreation(constructorMapping, innerCreation);
1 ✔
1274
      }
1275
    }
1276
  }
1 ✔
1277

1278
  private boolean applyNestedPendingConstructorCreations(ResultSetWrapper rsw, ResultMap resultMap,
1279
      MetaObject metaObject, String parentPrefix, CacheKey parentRowKey, boolean newObject, boolean foundValues) {
1280
    if (newObject) {
1 ✔
1281
      // new objects are linked by createResultObject
1282
      return false;
1 ✔
1283
    }
1284

1285
    for (ResultMapping constructorMapping : resultMap.getConstructorResultMappings()) {
1 ✔
1286
      final String nestedResultMapId = constructorMapping.getNestedResultMapId();
1 ✔
1287
      final Class<?> parameterType = constructorMapping.getJavaType();
1 ✔
1288
      if (nestedResultMapId == null || constructorMapping.getResultSet() != null || parameterType == null
1 !
1289
          || !objectFactory.isCollection(parameterType)) {
1 ✔
1290
        continue;
1 ✔
1291
      }
1292

1293
      try {
1294
        final String columnPrefix = getColumnPrefix(parentPrefix, constructorMapping);
1 ✔
1295
        final ResultMap nestedResultMap = getNestedResultMap(rsw, nestedResultMapId, columnPrefix);
1 ✔
1296

1297
        final CacheKey rowKey = createRowKey(nestedResultMap, rsw, columnPrefix);
1 ✔
1298
        final CacheKey combinedKey = combineKeys(rowKey, parentRowKey);
1 ✔
1299

1300
        // should have inserted already as a nested result object
1301
        Object rowValue = nestedResultObjects.get(combinedKey);
1 ✔
1302

1303
        PendingConstructorCreation pendingConstructorCreation = null;
1 ✔
1304
        if (rowValue instanceof PendingConstructorCreation) {
1 ✔
1305
          pendingConstructorCreation = (PendingConstructorCreation) rowValue;
1 ✔
1306
        } else if (rowValue != null) {
1 ✔
1307
          // found a simple object that was already linked/handled
1308
          continue;
1 ✔
1309
        }
1310

1311
        final boolean newValueForNestedResultMap = pendingConstructorCreation == null;
1 ✔
1312
        if (newValueForNestedResultMap) {
1 ✔
1313
          final Object parentObject = metaObject.getOriginalObject();
1 ✔
1314
          if (!(parentObject instanceof PendingConstructorCreation)) {
1 !
UNCOV
1315
            throw new ExecutorException(
×
1316
                "parentObject is not a pending creation, cannot continue linking! MyBatis internal error!");
1317
          }
1318

1319
          pendingConstructorCreation = (PendingConstructorCreation) parentObject;
1 ✔
1320
        }
1321

1322
        rowValue = getRowValue(rsw, nestedResultMap, combinedKey, columnPrefix,
1 ✔
1323
            newValueForNestedResultMap ? null : pendingConstructorCreation);
1 ✔
1324

1325
        if (rowValue == null) {
1 ✔
1326
          continue;
1 ✔
1327
        }
1328

1329
        if (rowValue instanceof PendingConstructorCreation) {
1 ✔
1330
          if (newValueForNestedResultMap) {
1 ✔
1331
            // we created a brand new pcc. this is a new collection value
1332
            pendingConstructorCreation.linkCreation(constructorMapping, (PendingConstructorCreation) rowValue);
1 ✔
1333
            foundValues = true;
1 ✔
1334
          }
1335
        } else {
1336
          pendingConstructorCreation.linkCollectionValue(constructorMapping, rowValue);
1 ✔
1337
          foundValues = true;
1 ✔
1338

1339
          if (combinedKey != CacheKey.NULL_CACHE_KEY) {
1 ✔
1340
            nestedResultObjects.put(combinedKey, pendingConstructorCreation);
1 ✔
1341
          }
1342
        }
UNCOV
1343
      } catch (SQLException e) {
×
UNCOV
1344
        throw new ExecutorException("Error getting constructor collection nested result map values for '"
×
UNCOV
1345
            + constructorMapping.getProperty() + "'.  Cause: " + e, e);
×
1346
      }
1 ✔
1347
    }
1 ✔
1348

1349
    return foundValues;
1 ✔
1350
  }
1351

1352
  private void createPendingConstructorCreations(Object rowValue) {
1353
    // handle possible pending creations within this object
1354
    // by now, the property mapping has been completely built, we can reconstruct it
1355
    final PendingRelation pendingRelation = pendingPccRelations.remove(rowValue);
1 ✔
1356
    final MetaObject metaObject = pendingRelation.metaObject;
1 ✔
1357
    final ResultMapping resultMapping = pendingRelation.propertyMapping;
1 ✔
1358

1359
    // get the list to be built
1360
    Object collectionProperty = instantiateCollectionPropertyIfAppropriate(resultMapping, metaObject);
1 ✔
1361
    if (collectionProperty != null) {
1 !
1362
      // we expect pending creations now
1363
      final Collection<Object> pendingCreations = (Collection<Object>) collectionProperty;
1 ✔
1364

1365
      // remove the link to the old collection
1366
      metaObject.setValue(resultMapping.getProperty(), null);
1 ✔
1367

1368
      // create new collection property
1369
      collectionProperty = instantiateCollectionPropertyIfAppropriate(resultMapping, metaObject);
1 ✔
1370
      final MetaObject targetMetaObject = configuration.newMetaObject(collectionProperty);
1 ✔
1371

1372
      // create the pending objects
1373
      for (Object pendingCreation : pendingCreations) {
1 ✔
1374
        if (pendingCreation instanceof PendingConstructorCreation) {
1 !
1375
          final PendingConstructorCreation pendingConstructorCreation = (PendingConstructorCreation) pendingCreation;
1 ✔
1376
          targetMetaObject.add(pendingConstructorCreation.create(objectFactory));
1 ✔
1377
        }
1378
      }
1 ✔
1379
    }
1380
  }
1 ✔
1381

1382
  private void verifyPendingCreationPreconditions(ResultMapping parentMapping) {
1383
    if (parentMapping != null) {
1 !
UNCOV
1384
      throw new ExecutorException(
×
1385
          "Cannot construct objects with collections in constructors using multiple result sets yet!");
1386
    }
1387

1388
    if (!mappedStatement.isResultOrdered()) {
1 !
UNCOV
1389
      throw new ExecutorException("Cannot reliably construct result if we are not sure the results are ordered "
×
1390
          + "so that no new previous rows would occur, set resultOrdered on your mapped statement if you have verified this");
1391
    }
1392
  }
1 ✔
1393

1394
  private void createAndStorePendingCreation(ResultHandler<?> resultHandler, ResultSet resultSet,
1395
      DefaultResultContext<Object> resultContext, PendingConstructorCreation pendingCreation) throws SQLException {
1396
    final Object result = pendingCreation.create(objectFactory);
1 ✔
1397
    storeObject(resultHandler, resultContext, result, null, resultSet);
1 ✔
1398
    nestedResultObjects.clear();
1 ✔
1399
  }
1 ✔
1400

1401
  //
1402
  // NESTED RESULT MAP (JOIN MAPPING)
1403
  //
1404

1405
  private boolean applyNestedResultMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject,
1406
      String parentPrefix, CacheKey parentRowKey, boolean newObject) {
1407
    boolean foundValues = false;
1 ✔
1408
    for (ResultMapping resultMapping : resultMap.getPropertyResultMappings()) {
1 ✔
1409
      final String nestedResultMapId = resultMapping.getNestedResultMapId();
1 ✔
1410
      if (nestedResultMapId != null && resultMapping.getResultSet() == null) {
1 !
1411
        try {
1412
          final String columnPrefix = getColumnPrefix(parentPrefix, resultMapping);
1 ✔
1413
          final ResultMap nestedResultMap = getNestedResultMap(rsw, nestedResultMapId, columnPrefix);
1 ✔
1414
          if (resultMapping.getColumnPrefix() == null) {
1 ✔
1415
            // try to fill circular reference only when columnPrefix
1416
            // is not specified for the nested result map (issue #215)
1417
            Object ancestorObject = ancestorObjects.get(nestedResultMapId);
1 ✔
1418
            if (ancestorObject != null) {
1 ✔
1419
              if (newObject) {
1 ✔
1420
                linkObjects(metaObject, resultMapping, ancestorObject); // issue #385
1 ✔
1421
              }
1422
              continue;
1 ✔
1423
            }
1424
          }
1425
          final CacheKey rowKey = createRowKey(nestedResultMap, rsw, columnPrefix);
1 ✔
1426
          final CacheKey combinedKey = combineKeys(rowKey, parentRowKey);
1 ✔
1427
          Object rowValue = nestedResultObjects.get(combinedKey);
1 ✔
1428
          boolean knownValue = rowValue != null;
1 ✔
1429
          instantiateCollectionPropertyIfAppropriate(resultMapping, metaObject); // mandatory
1 ✔
1430
          if (anyNotNullColumnHasValue(resultMapping, columnPrefix, rsw)) {
1 ✔
1431
            rowValue = getRowValue(rsw, nestedResultMap, combinedKey, columnPrefix, rowValue);
1 ✔
1432
            if (rowValue != null && !knownValue) {
1 ✔
1433
              linkObjects(metaObject, resultMapping, rowValue);
1 ✔
1434
              foundValues = true;
1 ✔
1435
            }
1436
          }
UNCOV
1437
        } catch (SQLException e) {
×
UNCOV
1438
          throw new ExecutorException(
×
UNCOV
1439
              "Error getting nested result map values for '" + resultMapping.getProperty() + "'.  Cause: " + e, e);
×
1440
        }
1 ✔
1441
      }
1442
    }
1 ✔
1443

1444
    // (issue #101)
1445
    if (resultMap.hasResultMapsUsingConstructorCollection()) {
1 ✔
1446
      foundValues = applyNestedPendingConstructorCreations(rsw, resultMap, metaObject, parentPrefix, parentRowKey,
1 ✔
1447
          newObject, foundValues);
1448
    }
1449

1450
    return foundValues;
1 ✔
1451
  }
1452

1453
  private String getColumnPrefix(String parentPrefix, ResultMapping resultMapping) {
1454
    final StringBuilder columnPrefixBuilder = new StringBuilder();
1 ✔
1455
    if (parentPrefix != null) {
1 ✔
1456
      columnPrefixBuilder.append(parentPrefix);
1 ✔
1457
    }
1458
    if (resultMapping.getColumnPrefix() != null) {
1 ✔
1459
      columnPrefixBuilder.append(resultMapping.getColumnPrefix());
1 ✔
1460
    }
1461
    return columnPrefixBuilder.length() == 0 ? null : columnPrefixBuilder.toString().toUpperCase(Locale.ENGLISH);
1 ✔
1462
  }
1463

1464
  private boolean anyNotNullColumnHasValue(ResultMapping resultMapping, String columnPrefix, ResultSetWrapper rsw)
1465
      throws SQLException {
1466
    Set<String> notNullColumns = resultMapping.getNotNullColumns();
1 ✔
1467
    if (notNullColumns != null && !notNullColumns.isEmpty()) {
1 ✔
1468
      ResultSet rs = rsw.getResultSet();
1 ✔
1469
      for (String column : notNullColumns) {
1 ✔
1470
        rs.getObject(prependPrefix(column, columnPrefix));
1 ✔
1471
        if (!rs.wasNull()) {
1 ✔
1472
          return true;
1 ✔
1473
        }
1474
      }
1 ✔
1475
      return false;
1 ✔
1476
    }
1477
    if (columnPrefix != null) {
1 ✔
1478
      for (String columnName : rsw.getColumnNames()) {
1 ✔
1479
        if (columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix.toUpperCase(Locale.ENGLISH))) {
1 ✔
1480
          return true;
1 ✔
1481
        }
1482
      }
1 ✔
1483
      return false;
1 ✔
1484
    }
1485
    return true;
1 ✔
1486
  }
1487

1488
  private ResultMap getNestedResultMap(ResultSetWrapper rsw, String nestedResultMapId, String columnPrefix)
1489
      throws SQLException {
1490
    ResultMap nestedResultMap = configuration.getResultMap(nestedResultMapId);
1 ✔
1491
    return resolveDiscriminatedResultMap(rsw, nestedResultMap, columnPrefix);
1 ✔
1492
  }
1493

1494
  //
1495
  // UNIQUE RESULT KEY
1496
  //
1497

1498
  private CacheKey createRowKey(ResultMap resultMap, ResultSetWrapper rsw, String columnPrefix) throws SQLException {
1499
    final CacheKey cacheKey = new CacheKey();
1 ✔
1500
    cacheKey.update(resultMap.getId());
1 ✔
1501
    List<ResultMapping> resultMappings = getResultMappingsForRowKey(resultMap);
1 ✔
1502
    if (resultMappings.isEmpty()) {
1 ✔
1503
      if (Map.class.isAssignableFrom(resultMap.getType())) {
1 !
UNCOV
1504
        createRowKeyForMap(rsw, cacheKey);
×
1505
      } else {
1506
        createRowKeyForUnmappedProperties(resultMap, rsw, cacheKey, columnPrefix);
1 ✔
1507
      }
1508
    } else {
1509
      createRowKeyForMappedProperties(resultMap, rsw, cacheKey, resultMappings, columnPrefix);
1 ✔
1510
    }
1511
    if (cacheKey.getUpdateCount() < 2) {
1 ✔
1512
      return CacheKey.NULL_CACHE_KEY;
1 ✔
1513
    }
1514
    return cacheKey;
1 ✔
1515
  }
1516

1517
  private CacheKey combineKeys(CacheKey rowKey, CacheKey parentRowKey) {
1518
    if (rowKey.getUpdateCount() > 1 && parentRowKey.getUpdateCount() > 1) {
1 ✔
1519
      CacheKey combinedKey;
1520
      try {
1521
        combinedKey = rowKey.clone();
1 ✔
UNCOV
1522
      } catch (CloneNotSupportedException e) {
×
UNCOV
1523
        throw new ExecutorException("Error cloning cache key.  Cause: " + e, e);
×
1524
      }
1 ✔
1525
      combinedKey.update(parentRowKey);
1 ✔
1526
      return combinedKey;
1 ✔
1527
    }
1528
    return CacheKey.NULL_CACHE_KEY;
1 ✔
1529
  }
1530

1531
  private List<ResultMapping> getResultMappingsForRowKey(ResultMap resultMap) {
1532
    List<ResultMapping> resultMappings = resultMap.getIdResultMappings();
1 ✔
1533
    if (resultMappings.isEmpty()) {
1 ✔
1534
      resultMappings = resultMap.getPropertyResultMappings();
1 ✔
1535
    }
1536
    return resultMappings;
1 ✔
1537
  }
1538

1539
  private void createRowKeyForMappedProperties(ResultMap resultMap, ResultSetWrapper rsw, CacheKey cacheKey,
1540
      List<ResultMapping> resultMappings, String columnPrefix) throws SQLException {
1541
    for (ResultMapping resultMapping : resultMappings) {
1 ✔
1542
      if (resultMapping.isSimple()) {
1 ✔
1543
        final String column = prependPrefix(resultMapping.getColumn(), columnPrefix);
1 ✔
1544
        TypeHandler<?> th = resultMapping.getTypeHandler();
1 ✔
1545
        Set<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix);
1 ✔
1546
        // Issue #114
1547
        if (column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH))) {
1 !
1548
          if (th == null) {
1 ✔
1549
            th = typeHandlerRegistry.getTypeHandler(rsw.getJdbcType(column));
1 ✔
1550
          }
1551
          if (th == null) {
1 ✔
1552
            th = ObjectTypeHandler.INSTANCE;
1 ✔
1553
          }
1554
          final Object value = th.getResult(rsw.getResultSet(), column);
1 ✔
1555
          if (value != null || configuration.isReturnInstanceForEmptyRow()) {
1 ✔
1556
            cacheKey.update(column);
1 ✔
1557
            cacheKey.update(value);
1 ✔
1558
          }
1559
        }
1560
      }
1561
    }
1 ✔
1562
  }
1 ✔
1563

1564
  private void createRowKeyForUnmappedProperties(ResultMap resultMap, ResultSetWrapper rsw, CacheKey cacheKey,
1565
      String columnPrefix) throws SQLException {
1566
    final MetaClass metaType = MetaClass.forClass(resultMap.getType(), reflectorFactory);
1 ✔
1567
    List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
1 ✔
1568
    for (String column : unmappedColumnNames) {
1 ✔
1569
      String property = column;
1 ✔
1570
      if (columnPrefix != null && !columnPrefix.isEmpty()) {
1 !
1571
        // When columnPrefix is specified, ignore columns without the prefix.
1572
        if (!column.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
1 ✔
1573
          continue;
1 ✔
1574
        }
1575
        property = column.substring(columnPrefix.length());
1 ✔
1576
      }
1577
      if (metaType.findProperty(property, configuration.isMapUnderscoreToCamelCase()) != null) {
1 ✔
1578
        String value = rsw.getResultSet().getString(column);
1 ✔
1579
        if (value != null) {
1 ✔
1580
          cacheKey.update(column);
1 ✔
1581
          cacheKey.update(value);
1 ✔
1582
        }
1583
      }
1584
    }
1 ✔
1585
  }
1 ✔
1586

1587
  private void createRowKeyForMap(ResultSetWrapper rsw, CacheKey cacheKey) throws SQLException {
1588
    List<String> columnNames = rsw.getColumnNames();
×
1589
    for (String columnName : columnNames) {
×
UNCOV
1590
      final String value = rsw.getResultSet().getString(columnName);
×
1591
      if (value != null) {
×
1592
        cacheKey.update(columnName);
×
UNCOV
1593
        cacheKey.update(value);
×
1594
      }
UNCOV
1595
    }
×
UNCOV
1596
  }
×
1597

1598
  private void linkObjects(MetaObject metaObject, ResultMapping resultMapping, Object rowValue) {
1599
    linkObjects(metaObject, resultMapping, rowValue, false);
1 ✔
1600
  }
1 ✔
1601

1602
  private void linkObjects(MetaObject metaObject, ResultMapping resultMapping, Object rowValue,
1603
      boolean isNestedCursorResult) {
1604
    final Object collectionProperty = instantiateCollectionPropertyIfAppropriate(resultMapping, metaObject);
1 ✔
1605
    if (collectionProperty != null) {
1 ✔
1606
      final MetaObject targetMetaObject = configuration.newMetaObject(collectionProperty);
1 ✔
1607
      if (isNestedCursorResult) {
1 !
UNCOV
1608
        targetMetaObject.addAll((List<?>) rowValue);
×
1609
      } else {
1610
        targetMetaObject.add(rowValue);
1 ✔
1611
      }
1612

1613
      // it is possible for pending creations to get set via property mappings,
1614
      // keep track of these, so we can rebuild them.
1615
      final Object originalObject = metaObject.getOriginalObject();
1 ✔
1616
      if (rowValue instanceof PendingConstructorCreation && !pendingPccRelations.containsKey(originalObject)) {
1 ✔
1617
        PendingRelation pendingRelation = new PendingRelation();
1 ✔
1618
        pendingRelation.propertyMapping = resultMapping;
1 ✔
1619
        pendingRelation.metaObject = metaObject;
1 ✔
1620

1621
        pendingPccRelations.put(originalObject, pendingRelation);
1 ✔
1622
      }
1623
    } else {
1 ✔
1624
      metaObject.setValue(resultMapping.getProperty(),
1 ✔
1625
          isNestedCursorResult ? toSingleObj((List<?>) rowValue) : rowValue);
1 !
1626
    }
1627
  }
1 ✔
1628

1629
  private Object toSingleObj(List<?> list) {
1630
    // Even if there are multiple elements, silently returns the first one.
UNCOV
1631
    return list.isEmpty() ? null : list.get(0);
×
1632
  }
1633

1634
  private Object instantiateCollectionPropertyIfAppropriate(ResultMapping resultMapping, MetaObject metaObject) {
1635
    final String propertyName = resultMapping.getProperty();
1 ✔
1636
    Object propertyValue = metaObject.getValue(propertyName);
1 ✔
1637
    if (propertyValue == null) {
1 ✔
1638
      Class<?> type = resultMapping.getJavaType();
1 ✔
1639
      if (type == null) {
1 ✔
1640
        type = metaObject.getSetterType(propertyName);
1 ✔
1641
      }
1642
      try {
1643
        if (objectFactory.isCollection(type)) {
1 ✔
1644
          propertyValue = objectFactory.create(type);
1 ✔
1645
          metaObject.setValue(propertyName, propertyValue);
1 ✔
1646
          return propertyValue;
1 ✔
1647
        }
UNCOV
1648
      } catch (Exception e) {
×
UNCOV
1649
        throw new ExecutorException(
×
UNCOV
1650
            "Error instantiating collection property for result '" + resultMapping.getProperty() + "'.  Cause: " + e,
×
1651
            e);
1652
      }
1 ✔
1653
    } else if (objectFactory.isCollection(propertyValue.getClass())) {
1 ✔
1654
      return propertyValue;
1 ✔
1655
    }
1656
    return null;
1 ✔
1657
  }
1658

1659
  private boolean hasTypeHandlerForResultObject(ResultSetWrapper rsw, Class<?> resultType) {
1660
    if (rsw.getColumnNames().size() == 1) {
1 ✔
1661
      return typeHandlerRegistry.hasTypeHandler(resultType, rsw.getJdbcType(rsw.getColumnNames().get(0)));
1 ✔
1662
    }
1663
    return typeHandlerRegistry.hasTypeHandler(resultType);
1 ✔
1664
  }
1665

1666
}
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