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

mybatis / mybatis-3 / 2686

01 Feb 2025 09:55PM UTC coverage: 87.093% (-0.1%) from 87.217%
2686

Pull #3379

github

web-flow
Merge c97c5c598 into 3d71c862a
Pull Request #3379: Resolve type handler based on `java.lang.reflect.Type` instead of `Class` and respect runtime JDBC type

3825 of 4663 branches covered (82.03%)

515 of 579 new or added lines in 36 files covered. (88.95%)

28 existing lines in 6 files now uncovered.

9912 of 11381 relevant lines covered (87.09%)

0.87 hits per line

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

90.86
/src/main/java/org/apache/ibatis/executor/resultset/DefaultResultSetHandler.java
1
/*
2
 *    Copyright 2009-2025 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.ResultSetMetaData;
24
import java.sql.SQLException;
25
import java.sql.Statement;
26
import java.text.MessageFormat;
27
import java.util.ArrayList;
28
import java.util.Arrays;
29
import java.util.Collection;
30
import java.util.HashMap;
31
import java.util.HashSet;
32
import java.util.IdentityHashMap;
33
import java.util.List;
34
import java.util.Locale;
35
import java.util.Map;
36
import java.util.Optional;
37
import java.util.Set;
38

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

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

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

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

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

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

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

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

113
  private final Map<CacheKey, TypeHandler<?>> typeHandlerCache = new HashMap<>();
1✔
114

115
  // temporary marking flag that indicate using constructor mapping (use field to reduce memory usage)
116
  private boolean useConstructorMappings;
117

118
  private static class PendingRelation {
119
    public MetaObject metaObject;
120
    public ResultMapping propertyMapping;
121
  }
122

123
  private static class UnMappedColumnAutoMapping {
124
    private final String column;
125
    private final String property;
126
    private final TypeHandler<?> typeHandler;
127
    private final boolean primitive;
128

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

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

151
  //
152
  // HANDLE OUTPUT PARAMETER
153
  //
154

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

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

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

218
    final List<Object> multipleResults = new ArrayList<>();
1✔
219

220
    int resultSetCount = 0;
1✔
221
    ResultSetWrapper rsw = getFirstResultSet(stmt);
1✔
222

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

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

249
    return collapseSingleResultList(multipleResults);
1✔
250
  }
251

252
  @Override
253
  public <E> Cursor<E> handleCursorResultSets(Statement stmt) throws SQLException {
254
    ErrorContext.instance().activity("handling cursor results").object(mappedStatement.getId());
1✔
255

256
    ResultSetWrapper rsw = getFirstResultSet(stmt);
1✔
257

258
    List<ResultMap> resultMaps = mappedStatement.getResultMaps();
1✔
259

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

266
    ResultMap resultMap = resultMaps.get(0);
1✔
267
    return new DefaultCursor<>(this, resultMap, rsw, rowBounds);
1✔
268
  }
269

270
  private ResultSetWrapper getFirstResultSet(Statement stmt) throws SQLException {
271
    ResultSet rs = null;
1✔
272
    SQLException e1 = null;
1✔
273

274
    try {
275
      rs = stmt.getResultSet();
1✔
276
    } catch (SQLException e) {
×
277
      // Oracle throws ORA-17283 for implicit cursor
278
      e1 = e;
×
279
    }
1✔
280

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

296
    return rs != null ? new ResultSetWrapper(rs, configuration) : null;
1✔
297
  }
298

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

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

322
  private void closeResultSet(ResultSet rs) {
323
    try {
324
      if (rs != null) {
1!
325
        rs.close();
1✔
326
      }
327
    } catch (SQLException e) {
×
328
      // ignore
329
    }
1✔
330
  }
1✔
331

332
  private void cleanUpAfterHandlingResultSet() {
333
    nestedResultObjects.clear();
1✔
334
  }
1✔
335

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

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

362
  @SuppressWarnings("unchecked")
363
  private List<Object> collapseSingleResultList(List<Object> multipleResults) {
364
    return multipleResults.size() == 1 ? (List<Object>) multipleResults.get(0) : multipleResults;
1✔
365
  }
366

367
  //
368
  // HANDLE ROWS FOR SIMPLE RESULTMAP
369
  //
370

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

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

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

400
  private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap,
401
      ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
402
    final boolean useCollectionConstructorInjection = resultMap.hasResultMapsUsingConstructorCollection();
1✔
403

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

417
        createAndStorePendingCreation(resultHandler, resultSet, resultContext, (PendingConstructorCreation) rowValue);
×
418
      }
419
    }
1✔
420
  }
1✔
421

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

429
    if (pendingPccRelations.containsKey(rowValue)) {
1✔
430
      createPendingConstructorCreations(rowValue);
1✔
431
    }
432

433
    callResultHandler(resultHandler, resultContext, rowValue);
1✔
434
  }
1✔
435

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

443
  private boolean shouldProcessMoreRows(ResultContext<?> context, RowBounds rowBounds) {
444
    return !context.isStopped() && context.getResultCount() < rowBounds.getLimit();
1✔
445
  }
446

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

461
  //
462
  // GET VALUE FROM ROW FOR SIMPLE RESULT MAP
463
  //
464

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

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

485
      if (combinedKey != CacheKey.NULL_CACHE_KEY) {
1✔
486
        nestedResultObjects.put(combinedKey, rowValue);
1✔
487
      }
488
    }
489

490
    return rowValue;
1✔
491
  }
492

493
  //
494
  // GET VALUE FROM ROW FOR NESTED RESULT MAP
495
  //
496

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

530
  private void putAncestor(Object resultObject, String resultMapId) {
531
    ancestorObjects.put(resultMapId, resultObject);
1✔
532
  }
1✔
533

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

545
  //
546
  // PROPERTY MAPPINGS
547
  //
548

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

586
  private Object getPropertyMappingValue(ResultSetWrapper rsw, MetaObject metaResultObject,
587
      ResultMapping propertyMapping, ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException {
588
    final ResultSet rs = rsw.getResultSet();
1✔
589
    final String property = propertyMapping.getProperty();
1✔
590
    if (propertyMapping.getNestedQueryId() != null) {
1✔
591
      return getNestedQueryMappingValue(rsw, metaResultObject, propertyMapping, lazyLoader, columnPrefix);
1✔
592
    }
593
    if (JdbcType.CURSOR.equals(propertyMapping.getJdbcType())) {
1!
NEW
594
      List<Object> results = getNestedCursorValue(rsw, propertyMapping, columnPrefix);
×
595
      linkObjects(metaResultObject, propertyMapping, results.get(0), true);
×
596
      return metaResultObject.getValue(propertyMapping.getProperty());
×
597
    }
598
    if (propertyMapping.getResultSet() != null) {
1✔
599
      addPendingChildRelation(rs, metaResultObject, propertyMapping); // TODO is that OK?
1✔
600
      return DEFERRED;
1✔
601
    } else {
602
      final String column = prependPrefix(propertyMapping.getColumn(), columnPrefix);
1✔
603
      TypeHandler<?> typeHandler = propertyMapping.getTypeHandler();
1✔
604
      if (typeHandler == null) {
1✔
605
        typeHandler = resolvePropertyTypeHandler(rsw, metaResultObject, property, column);
1✔
606
      }
607
      return typeHandler.getResult(rs, column);
1✔
608
    }
609
  }
610

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

624
  private TypeHandler<?> resolvePropertyTypeHandler(ResultSetWrapper rsw, MetaObject metaResultObject,
625
      final String property, final String column) {
626
    CacheKey typeHandlerCacheKey = new CacheKey();
1✔
627
    Class<?> metaResultObjectClass = metaResultObject.getOriginalObject().getClass();
1✔
628
    typeHandlerCacheKey.update(metaResultObjectClass);
1✔
629
    typeHandlerCacheKey.update(column);
1✔
630
    typeHandlerCacheKey.update(property);
1✔
631
    return typeHandlerCache.computeIfAbsent(typeHandlerCacheKey, k -> {
1✔
632
      final JdbcType jdbcType = rsw.getJdbcType(column);
1✔
633
      final TypeHandler<?> th;
634
      if (property == null) {
1✔
635
        th = typeHandlerRegistry.getTypeHandler(jdbcType);
1✔
636
      } else {
637
        Type classToHandle = metaResultObject.getGenericSetterType(property).getKey();
1✔
638
        th = configuration.getTypeHandlerRegistry().resolve(metaResultObjectClass, classToHandle, property, jdbcType,
1✔
639
            null);
640
        if (th == null) {
1✔
641
          throw new TypeException(
1✔
642
              "No usable type handler found for mapping the result of column '" + column + "' to property '" + property
643
                  + "'. It was either not specified and/or could not be found for the javaType (" + classToHandle
644
                  + ") : jdbcType (" + jdbcType + ") combination.");
645
        }
646
      }
647
      return th;
1✔
648
    });
649
  }
650

651
  private List<UnMappedColumnAutoMapping> createAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap,
652
      MetaObject metaObject, String columnPrefix) throws SQLException {
653
    final String mapKey = resultMap.getId() + ":" + columnPrefix;
1✔
654
    List<UnMappedColumnAutoMapping> autoMapping = autoMappingsCache.get(mapKey);
1✔
655
    if (autoMapping == null) {
1✔
656
      autoMapping = new ArrayList<>();
1✔
657
      final List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
1✔
658
      // Remove the entry to release the memory
659
      List<String> mappedInConstructorAutoMapping = constructorAutoMappingColumns.remove(mapKey);
1✔
660
      if (mappedInConstructorAutoMapping != null) {
1✔
661
        unmappedColumnNames.removeAll(mappedInConstructorAutoMapping);
1✔
662
      }
663
      for (String columnName : unmappedColumnNames) {
1✔
664
        String propertyName = columnName;
1✔
665
        if (columnPrefix != null && !columnPrefix.isEmpty()) {
1!
666
          // When columnPrefix is specified,
667
          // ignore columns without the prefix.
668
          if (!columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
1✔
669
            continue;
1✔
670
          }
671
          propertyName = columnName.substring(columnPrefix.length());
1✔
672
        }
673
        final String property = metaObject.findProperty(propertyName, configuration.isMapUnderscoreToCamelCase());
1✔
674
        if (property != null && metaObject.hasSetter(property)) {
1✔
675
          if (resultMap.getMappedProperties().contains(property)) {
1✔
676
            continue;
1✔
677
          }
678
          final Type propertyType = metaObject.getGenericSetterType(property).getKey();
1✔
679
          Class<?> metaObjectClass = metaObject.getOriginalObject().getClass();
1✔
680
          TypeHandler<?> typeHandler = configuration.getTypeHandlerRegistry().resolve(metaObjectClass, propertyType,
1✔
681
              property, rsw.getJdbcType(columnName), null);
1✔
682
          if (typeHandler != null) {
1✔
683
            autoMapping.add(new UnMappedColumnAutoMapping(columnName, property, typeHandler,
1✔
684
                propertyType instanceof Class && ((Class<?>) propertyType).isPrimitive()));
1✔
685
          } else {
686
            configuration.getAutoMappingUnknownColumnBehavior().doAction(mappedStatement, columnName, property,
1✔
687
                propertyType);
688
          }
689
        } else {
1✔
690
          configuration.getAutoMappingUnknownColumnBehavior().doAction(mappedStatement, columnName,
1✔
691
              property != null ? property : propertyName, null);
1✔
692
        }
693
      }
1✔
694
      autoMappingsCache.put(mapKey, autoMapping);
1✔
695
    }
696
    return autoMapping;
1✔
697
  }
698

699
  private boolean applyAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject,
700
      String columnPrefix) throws SQLException {
701
    List<UnMappedColumnAutoMapping> autoMapping = createAutomaticMappings(rsw, resultMap, metaObject, columnPrefix);
1✔
702
    boolean foundValues = false;
1✔
703
    if (!autoMapping.isEmpty()) {
1✔
704
      for (UnMappedColumnAutoMapping mapping : autoMapping) {
1✔
705
        final Object value = mapping.typeHandler.getResult(rsw.getResultSet(), mapping.column);
1✔
706
        if (value != null) {
1✔
707
          foundValues = true;
1✔
708
        }
709
        if (value != null || configuration.isCallSettersOnNulls() && !mapping.primitive) {
1!
710
          // gcode issue #377, call setter on nulls (value is not 'found')
711
          metaObject.setValue(mapping.property, value);
1✔
712
        }
713
      }
1✔
714
    }
715
    return foundValues;
1✔
716
  }
717

718
  // MULTIPLE RESULT SETS
719

720
  private void linkToParents(ResultSet rs, ResultMapping parentMapping, Object rowValue) throws SQLException {
721
    CacheKey parentKey = createKeyForMultipleResults(rs, parentMapping, parentMapping.getColumn(),
1✔
722
        parentMapping.getForeignColumn());
1✔
723
    List<PendingRelation> parents = pendingRelations.get(parentKey);
1✔
724
    if (parents != null) {
1✔
725
      for (PendingRelation parent : parents) {
1✔
726
        if (parent != null && rowValue != null) {
1!
727
          linkObjects(parent.metaObject, parent.propertyMapping, rowValue);
1✔
728
        }
729
      }
1✔
730
    }
731
  }
1✔
732

733
  private void addPendingChildRelation(ResultSet rs, MetaObject metaResultObject, ResultMapping parentMapping)
734
      throws SQLException {
735
    CacheKey cacheKey = createKeyForMultipleResults(rs, parentMapping, parentMapping.getColumn(),
1✔
736
        parentMapping.getColumn());
1✔
737
    PendingRelation deferLoad = new PendingRelation();
1✔
738
    deferLoad.metaObject = metaResultObject;
1✔
739
    deferLoad.propertyMapping = parentMapping;
1✔
740
    List<PendingRelation> relations = pendingRelations.computeIfAbsent(cacheKey, k -> new ArrayList<>());
1✔
741
    // issue #255
742
    relations.add(deferLoad);
1✔
743
    ResultMapping previous = nextResultMaps.get(parentMapping.getResultSet());
1✔
744
    if (previous == null) {
1✔
745
      nextResultMaps.put(parentMapping.getResultSet(), parentMapping);
1✔
746
    } else if (!previous.equals(parentMapping)) {
1!
747
      throw new ExecutorException("Two different properties are mapped to the same resultSet");
×
748
    }
749
  }
1✔
750

751
  private CacheKey createKeyForMultipleResults(ResultSet rs, ResultMapping resultMapping, String names, String columns)
752
      throws SQLException {
753
    CacheKey cacheKey = new CacheKey();
1✔
754
    cacheKey.update(resultMapping);
1✔
755
    if (columns != null && names != null) {
1!
756
      String[] columnsArray = columns.split(",");
1✔
757
      String[] namesArray = names.split(",");
1✔
758
      for (int i = 0; i < columnsArray.length; i++) {
1✔
759
        Object value = rs.getString(columnsArray[i]);
1✔
760
        if (value != null) {
1!
761
          cacheKey.update(namesArray[i]);
1✔
762
          cacheKey.update(value);
1✔
763
        }
764
      }
765
    }
766
    return cacheKey;
1✔
767
  }
768

769
  //
770
  // INSTANTIATION & CONSTRUCTOR MAPPING
771
  //
772

773
  private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, ResultLoaderMap lazyLoader,
774
      String columnPrefix, CacheKey parentRowKey) throws SQLException {
775
    this.useConstructorMappings = false; // reset previous mapping result
1✔
776
    final List<Class<?>> constructorArgTypes = new ArrayList<>();
1✔
777
    final List<Object> constructorArgs = new ArrayList<>();
1✔
778

779
    Object resultObject = createResultObject(rsw, resultMap, constructorArgTypes, constructorArgs, columnPrefix,
1✔
780
        parentRowKey);
781
    if (resultObject != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
1✔
782
      final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings();
1✔
783
      for (ResultMapping propertyMapping : propertyMappings) {
1✔
784
        // issue gcode #109 && issue #149
785
        if (propertyMapping.getNestedQueryId() != null && propertyMapping.isLazy()) {
1✔
786
          resultObject = configuration.getProxyFactory().createProxy(resultObject, lazyLoader, configuration,
1✔
787
              objectFactory, constructorArgTypes, constructorArgs);
788
          break;
1✔
789
        }
790
      }
1✔
791

792
      // (issue #101)
793
      if (resultMap.hasResultMapsUsingConstructorCollection() && resultObject instanceof PendingConstructorCreation) {
1!
794
        linkNestedPendingCreations(rsw, resultMap, columnPrefix, parentRowKey,
1✔
795
            (PendingConstructorCreation) resultObject, constructorArgs);
796
      }
797
    }
798

799
    this.useConstructorMappings = resultObject != null && !constructorArgTypes.isEmpty(); // set current mapping result
1✔
800
    return resultObject;
1✔
801
  }
802

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

806
    final Class<?> resultType = resultMap.getType();
1✔
807
    final MetaClass metaType = MetaClass.forClass(resultType, reflectorFactory);
1✔
808
    final List<ResultMapping> constructorMappings = resultMap.getConstructorResultMappings();
1✔
809
    if (hasTypeHandlerForResultObject(rsw, resultType)) {
1✔
810
      return createPrimitiveResultObject(rsw, resultMap, columnPrefix);
1✔
811
    }
812
    if (!constructorMappings.isEmpty()) {
1✔
813
      return createParameterizedResultObject(rsw, resultType, constructorMappings, constructorArgTypes, constructorArgs,
1✔
814
          columnPrefix, resultMap.hasResultMapsUsingConstructorCollection(), parentRowKey);
1✔
815
    } else if (resultType.isInterface() || metaType.hasDefaultConstructor()) {
1✔
816
      return objectFactory.create(resultType);
1✔
817
    } else if (shouldApplyAutomaticMappings(resultMap, false)) {
1!
818
      return createByConstructorSignature(rsw, resultMap, columnPrefix, resultType, constructorArgTypes,
1✔
819
          constructorArgs);
820
    }
821
    throw new ExecutorException("Do not know how to create an instance of " + resultType);
×
822
  }
823

824
  Object createParameterizedResultObject(ResultSetWrapper rsw, Class<?> resultType,
825
      List<ResultMapping> constructorMappings, List<Class<?>> constructorArgTypes, List<Object> constructorArgs,
826
      String columnPrefix, boolean useCollectionConstructorInjection, CacheKey parentRowKey) {
827
    boolean foundValues = false;
1✔
828

829
    for (ResultMapping constructorMapping : constructorMappings) {
1✔
830
      final Class<?> parameterType = constructorMapping.getJavaType();
1✔
831
      final String column = constructorMapping.getColumn();
1✔
832
      final Object value;
833
      try {
834
        if (constructorMapping.getNestedQueryId() != null) {
1✔
835
          value = getNestedQueryConstructorValue(rsw, constructorMapping, columnPrefix);
1✔
836
        } else if (JdbcType.CURSOR.equals(constructorMapping.getJdbcType())) {
1!
NEW
837
          List<?> result = (List<?>) getNestedCursorValue(rsw, constructorMapping, columnPrefix).get(0);
×
838
          if (objectFactory.isCollection(parameterType)) {
×
839
            MetaObject collection = configuration.newMetaObject(objectFactory.create(parameterType));
×
840
            collection.addAll((List<?>) result);
×
841
            value = collection.getOriginalObject();
×
842
          } else {
×
843
            value = toSingleObj(result);
×
844
          }
845
        } else if (constructorMapping.getNestedResultMapId() != null) {
1✔
846
          final String constructorColumnPrefix = getColumnPrefix(columnPrefix, constructorMapping);
1✔
847
          final ResultMap resultMap = resolveDiscriminatedResultMap(rsw,
1✔
848
              configuration.getResultMap(constructorMapping.getNestedResultMapId()), constructorColumnPrefix);
1✔
849
          value = getRowValue(rsw, resultMap, constructorColumnPrefix,
1✔
850
              useCollectionConstructorInjection ? parentRowKey : null);
1✔
851
        } else {
1✔
852
          TypeHandler<?> typeHandler = constructorMapping.getTypeHandler();
1✔
853
          if (typeHandler == null) {
1✔
854
            typeHandler = typeHandlerRegistry.getTypeHandler(constructorMapping.getJavaType(), rsw.getJdbcType(column));
1✔
855
          }
856
          value = typeHandler.getResult(rsw.getResultSet(), prependPrefix(column, columnPrefix));
1✔
857
        }
858
      } catch (ResultMapException | SQLException e) {
1✔
859
        throw new ExecutorException("Could not process result for mapping: " + constructorMapping, e);
1✔
860
      }
1✔
861

862
      constructorArgTypes.add(parameterType);
1✔
863
      constructorArgs.add(value);
1✔
864

865
      foundValues = value != null || foundValues;
1✔
866
    }
1✔
867

868
    if (!foundValues) {
1✔
869
      return null;
1✔
870
    }
871

872
    if (useCollectionConstructorInjection) {
1✔
873
      // at least one of the nestedResultMaps contained a collection, we have to defer until later
874
      return new PendingConstructorCreation(resultType, constructorArgTypes, constructorArgs);
1✔
875
    }
876

877
    return objectFactory.create(resultType, constructorArgTypes, constructorArgs);
1✔
878
  }
879

880
  private Object createByConstructorSignature(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix,
881
      Class<?> resultType, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) throws SQLException {
882
    return applyConstructorAutomapping(rsw, resultMap, columnPrefix, resultType, constructorArgTypes, constructorArgs,
1✔
883
        findConstructorForAutomapping(resultType, rsw).orElseThrow(() -> new ExecutorException(
1✔
884
            "No constructor found in " + resultType.getName() + " matching " + rsw.getClassNames())));
×
885
  }
886

887
  private Optional<Constructor<?>> findConstructorForAutomapping(final Class<?> resultType, ResultSetWrapper rsw) {
888
    Constructor<?>[] constructors = resultType.getDeclaredConstructors();
1✔
889
    if (constructors.length == 1) {
1✔
890
      return Optional.of(constructors[0]);
1✔
891
    }
892
    Optional<Constructor<?>> annotated = Arrays.stream(constructors)
1✔
893
        .filter(x -> x.isAnnotationPresent(AutomapConstructor.class)).reduce((x, y) -> {
1✔
894
          throw new ExecutorException("@AutomapConstructor should be used in only one constructor.");
1✔
895
        });
896
    if (annotated.isPresent()) {
1✔
897
      return annotated;
1✔
898
    }
899
    if (configuration.isArgNameBasedConstructorAutoMapping()) {
1!
900
      // Finding-best-match type implementation is possible,
901
      // but using @AutomapConstructor seems sufficient.
902
      throw new ExecutorException(MessageFormat.format(
×
903
          "'argNameBasedConstructorAutoMapping' is enabled and the class ''{0}'' has multiple constructors, so @AutomapConstructor must be added to one of the constructors.",
904
          resultType.getName()));
×
905
    } else {
906
      return Arrays.stream(constructors).filter(x -> findUsableConstructorByArgTypes(x, rsw.getJdbcTypes())).findAny();
1✔
907
    }
908
  }
909

910
  private boolean findUsableConstructorByArgTypes(final Constructor<?> constructor, final List<JdbcType> jdbcTypes) {
911
    final Class<?>[] parameterTypes = constructor.getParameterTypes();
1✔
912
    if (parameterTypes.length != jdbcTypes.size()) {
1✔
913
      return false;
1✔
914
    }
915
    for (int i = 0; i < parameterTypes.length; i++) {
1✔
916
      if (!typeHandlerRegistry.hasTypeHandler(parameterTypes[i], jdbcTypes.get(i))) {
1!
917
        return false;
×
918
      }
919
    }
920
    return true;
1✔
921
  }
922

923
  private Object applyConstructorAutomapping(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix,
924
      Class<?> resultType, List<Class<?>> constructorArgTypes, List<Object> constructorArgs, Constructor<?> constructor)
925
      throws SQLException {
926
    boolean foundValues = false;
1✔
927
    if (configuration.isArgNameBasedConstructorAutoMapping()) {
1✔
928
      foundValues = applyArgNameBasedConstructorAutoMapping(rsw, resultMap, columnPrefix, constructorArgTypes,
1✔
929
          constructorArgs, constructor, foundValues);
930
    } else {
931
      foundValues = applyColumnOrderBasedConstructorAutomapping(rsw, constructorArgTypes, constructorArgs, constructor,
1✔
932
          foundValues);
933
    }
934
    return foundValues || configuration.isReturnInstanceForEmptyRow()
1!
935
        ? objectFactory.create(resultType, constructorArgTypes, constructorArgs) : null;
1✔
936
  }
937

938
  private boolean applyColumnOrderBasedConstructorAutomapping(ResultSetWrapper rsw, List<Class<?>> constructorArgTypes,
939
      List<Object> constructorArgs, Constructor<?> constructor, boolean foundValues) throws SQLException {
940
    Class<?>[] parameterTypes = constructor.getParameterTypes();
1✔
941

942
    if (parameterTypes.length > rsw.getClassNames().size()) {
1✔
943
      throw new ExecutorException(MessageFormat.format(
1✔
944
          "Constructor auto-mapping of ''{0}'' failed. The constructor takes ''{1}'' arguments, but there are only ''{2}'' columns in the result set.",
945
          constructor, parameterTypes.length, rsw.getClassNames().size()));
1✔
946
    }
947

948
    for (int i = 0; i < parameterTypes.length; i++) {
1✔
949
      Class<?> parameterType = parameterTypes[i];
1✔
950
      String columnName = rsw.getColumnNames().get(i);
1✔
951
      TypeHandler<?> typeHandler = rsw.getTypeHandler(parameterType, columnName);
1✔
952
      Object value = typeHandler.getResult(rsw.getResultSet(), columnName);
1✔
953
      constructorArgTypes.add(parameterType);
1✔
954
      constructorArgs.add(value);
1✔
955
      foundValues = value != null || foundValues;
1!
956
    }
957
    return foundValues;
1✔
958
  }
959

960
  private boolean applyArgNameBasedConstructorAutoMapping(ResultSetWrapper rsw, ResultMap resultMap,
961
      String columnPrefix, List<Class<?>> constructorArgTypes, List<Object> constructorArgs, Constructor<?> constructor,
962
      boolean foundValues) throws SQLException {
963
    List<String> missingArgs = null;
1✔
964
    Parameter[] params = constructor.getParameters();
1✔
965
    for (Parameter param : params) {
1✔
966
      boolean columnNotFound = true;
1✔
967
      Param paramAnno = param.getAnnotation(Param.class);
1✔
968
      String paramName = paramAnno == null ? param.getName() : paramAnno.value();
1✔
969
      for (String columnName : rsw.getColumnNames()) {
1✔
970
        if (columnMatchesParam(columnName, paramName, columnPrefix)) {
1✔
971
          Class<?> paramType = param.getType();
1✔
972
          TypeHandler<?> typeHandler = rsw.getTypeHandler(paramType, columnName);
1✔
973
          Object value = typeHandler.getResult(rsw.getResultSet(), columnName);
1✔
974
          constructorArgTypes.add(paramType);
1✔
975
          constructorArgs.add(value);
1✔
976
          final String mapKey = resultMap.getId() + ":" + columnPrefix;
1✔
977
          if (!autoMappingsCache.containsKey(mapKey)) {
1!
978
            constructorAutoMappingColumns.computeIfAbsent(mapKey, k -> new ArrayList<>()).add(columnName);
1✔
979
          }
980
          columnNotFound = false;
1✔
981
          foundValues = value != null || foundValues;
1!
982
        }
983
      }
1✔
984
      if (columnNotFound) {
1✔
985
        if (missingArgs == null) {
1!
986
          missingArgs = new ArrayList<>();
1✔
987
        }
988
        missingArgs.add(paramName);
1✔
989
      }
990
    }
991
    if (foundValues && constructorArgs.size() < params.length) {
1✔
992
      throw new ExecutorException(MessageFormat.format(
1✔
993
          "Constructor auto-mapping of ''{1}'' failed " + "because ''{0}'' were not found in the result set; "
994
              + "Available columns are ''{2}'' and mapUnderscoreToCamelCase is ''{3}''.",
995
          missingArgs, constructor, rsw.getColumnNames(), configuration.isMapUnderscoreToCamelCase()));
1✔
996
    }
997
    return foundValues;
1✔
998
  }
999

1000
  private boolean columnMatchesParam(String columnName, String paramName, String columnPrefix) {
1001
    if (columnPrefix != null) {
1✔
1002
      if (!columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
1✔
1003
        return false;
1✔
1004
      }
1005
      columnName = columnName.substring(columnPrefix.length());
1✔
1006
    }
1007
    return paramName
1✔
1008
        .equalsIgnoreCase(configuration.isMapUnderscoreToCamelCase() ? columnName.replace("_", "") : columnName);
1✔
1009
  }
1010

1011
  private Object createPrimitiveResultObject(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix)
1012
      throws SQLException {
1013
    final Class<?> resultType = resultMap.getType();
1✔
1014
    final String columnName;
1015
    if (!resultMap.getResultMappings().isEmpty()) {
1✔
1016
      final List<ResultMapping> resultMappingList = resultMap.getResultMappings();
1✔
1017
      final ResultMapping mapping = resultMappingList.get(0);
1✔
1018
      columnName = prependPrefix(mapping.getColumn(), columnPrefix);
1✔
1019
    } else {
1✔
1020
      columnName = rsw.getColumnNames().get(0);
1✔
1021
    }
1022
    final TypeHandler<?> typeHandler = rsw.getTypeHandler(resultType, columnName);
1✔
1023
    return typeHandler.getResult(rsw.getResultSet(), columnName);
1✔
1024
  }
1025

1026
  //
1027
  // NESTED QUERY
1028
  //
1029

1030
  private Object getNestedQueryConstructorValue(ResultSetWrapper rsw, ResultMapping constructorMapping,
1031
      String columnPrefix) throws SQLException {
1032
    final String nestedQueryId = constructorMapping.getNestedQueryId();
1✔
1033
    final MappedStatement nestedQuery = configuration.getMappedStatement(nestedQueryId);
1✔
1034
    final Class<?> nestedQueryParameterType = nestedQuery.getParameterMap().getType();
1✔
1035
    final Object nestedQueryParameterObject = prepareParameterForNestedQuery(rsw, constructorMapping,
1✔
1036
        nestedQueryParameterType, columnPrefix);
1037
    Object value = null;
1✔
1038
    if (nestedQueryParameterObject != null) {
1!
1039
      final BoundSql nestedBoundSql = nestedQuery.getBoundSql(nestedQueryParameterObject);
1✔
1040
      final CacheKey key = executor.createCacheKey(nestedQuery, nestedQueryParameterObject, RowBounds.DEFAULT,
1✔
1041
          nestedBoundSql);
1042
      final Class<?> targetType = constructorMapping.getJavaType();
1✔
1043
      final ResultLoader resultLoader = new ResultLoader(configuration, executor, nestedQuery,
1✔
1044
          nestedQueryParameterObject, targetType, key, nestedBoundSql);
1045
      value = resultLoader.loadResult();
1✔
1046
    }
1047
    return value;
1✔
1048
  }
1049

1050
  private Object getNestedQueryMappingValue(ResultSetWrapper rsw, MetaObject metaResultObject,
1051
      ResultMapping propertyMapping, ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException {
1052
    final String nestedQueryId = propertyMapping.getNestedQueryId();
1✔
1053
    final String property = propertyMapping.getProperty();
1✔
1054
    final MappedStatement nestedQuery = configuration.getMappedStatement(nestedQueryId);
1✔
1055
    final Class<?> nestedQueryParameterType = nestedQuery.getParameterMap().getType();
1✔
1056
    final Object nestedQueryParameterObject = prepareParameterForNestedQuery(rsw, propertyMapping,
1✔
1057
        nestedQueryParameterType, columnPrefix);
1058
    Object value = null;
1✔
1059
    if (nestedQueryParameterObject != null) {
1✔
1060
      final BoundSql nestedBoundSql = nestedQuery.getBoundSql(nestedQueryParameterObject);
1✔
1061
      final CacheKey key = executor.createCacheKey(nestedQuery, nestedQueryParameterObject, RowBounds.DEFAULT,
1✔
1062
          nestedBoundSql);
1063
      final Class<?> targetType = propertyMapping.getJavaType();
1✔
1064
      if (executor.isCached(nestedQuery, key)) {
1✔
1065
        executor.deferLoad(nestedQuery, metaResultObject, property, key, targetType);
1✔
1066
        value = DEFERRED;
1✔
1067
      } else {
1068
        final ResultLoader resultLoader = new ResultLoader(configuration, executor, nestedQuery,
1✔
1069
            nestedQueryParameterObject, targetType, key, nestedBoundSql);
1070
        if (propertyMapping.isLazy()) {
1✔
1071
          lazyLoader.addLoader(property, metaResultObject, resultLoader);
1✔
1072
          value = DEFERRED;
1✔
1073
        } else {
1074
          value = resultLoader.loadResult();
1✔
1075
        }
1076
      }
1077
    }
1078
    return value;
1✔
1079
  }
1080

1081
  private Object prepareParameterForNestedQuery(ResultSetWrapper rsw, ResultMapping resultMapping,
1082
      Class<?> parameterType, String columnPrefix) throws SQLException {
1083
    if (resultMapping.isCompositeResult()) {
1✔
1084
      return prepareCompositeKeyParameter(rsw, resultMapping, parameterType, columnPrefix);
1✔
1085
    }
1086
    return prepareSimpleKeyParameter(rsw, resultMapping, parameterType, columnPrefix);
1✔
1087
  }
1088

1089
  private Object prepareSimpleKeyParameter(ResultSetWrapper rsw, ResultMapping resultMapping, Class<?> parameterType,
1090
      String columnPrefix) throws SQLException {
1091
    final String columnName = prependPrefix(resultMapping.getColumn(), columnPrefix);
1✔
1092
    final TypeHandler<?> typeHandler = rsw.getTypeHandler(parameterType, columnName);
1✔
1093
    return typeHandler.getResult(rsw.getResultSet(), columnName);
1✔
1094
  }
1095

1096
  private Object prepareCompositeKeyParameter(ResultSetWrapper rsw, ResultMapping resultMapping, Class<?> parameterType,
1097
      String columnPrefix) throws SQLException {
1098
    final Object parameterObject = instantiateParameterObject(parameterType);
1✔
1099
    final MetaObject metaObject = configuration.newMetaObject(parameterObject);
1✔
1100
    boolean foundValues = false;
1✔
1101
    for (ResultMapping innerResultMapping : resultMapping.getComposites()) {
1✔
1102
      final Class<?> propType = metaObject.getSetterType(innerResultMapping.getProperty());
1✔
1103
      final TypeHandler<?> typeHandler = typeHandlerRegistry.getTypeHandler(propType);
1✔
1104
      final Object propValue = typeHandler.getResult(rsw.getResultSet(),
1✔
1105
          prependPrefix(innerResultMapping.getColumn(), columnPrefix));
1✔
1106
      // issue #353 & #560 do not execute nested query if key is null
1107
      if (propValue != null) {
1✔
1108
        metaObject.setValue(innerResultMapping.getProperty(), propValue);
1✔
1109
        foundValues = true;
1✔
1110
      }
1111
    }
1✔
1112
    return foundValues ? parameterObject : null;
1✔
1113
  }
1114

1115
  private Object instantiateParameterObject(Class<?> parameterType) {
1116
    if (parameterType == null) {
1✔
1117
      return new HashMap<>();
1✔
1118
    }
1119
    if (ParamMap.class.equals(parameterType)) {
1✔
1120
      return new HashMap<>(); // issue #649
1✔
1121
    } else {
1122
      return objectFactory.create(parameterType);
1✔
1123
    }
1124
  }
1125

1126
  //
1127
  // DISCRIMINATOR
1128
  //
1129

1130
  public ResultMap resolveDiscriminatedResultMap(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix)
1131
      throws SQLException {
1132
    Set<String> pastDiscriminators = new HashSet<>();
1✔
1133
    Discriminator discriminator = resultMap.getDiscriminator();
1✔
1134
    while (discriminator != null) {
1✔
1135
      final Object value = getDiscriminatorValue(rsw, discriminator, columnPrefix);
1✔
1136
      final String discriminatedMapId = discriminator.getMapIdFor(String.valueOf(value));
1✔
1137
      if (!configuration.hasResultMap(discriminatedMapId)) {
1✔
1138
        break;
1✔
1139
      }
1140
      resultMap = configuration.getResultMap(discriminatedMapId);
1✔
1141
      Discriminator lastDiscriminator = discriminator;
1✔
1142
      discriminator = resultMap.getDiscriminator();
1✔
1143
      if (discriminator == lastDiscriminator || !pastDiscriminators.add(discriminatedMapId)) {
1!
1144
        break;
1✔
1145
      }
1146
    }
1✔
1147
    return resultMap;
1✔
1148
  }
1149

1150
  private Object getDiscriminatorValue(ResultSetWrapper rsw, Discriminator discriminator, String columnPrefix)
1151
      throws SQLException {
1152
    final ResultMapping resultMapping = discriminator.getResultMapping();
1✔
1153
    String column = prependPrefix(resultMapping.getColumn(), columnPrefix);
1✔
1154
    TypeHandler<?> typeHandler = resultMapping.getTypeHandler();
1✔
1155
    if (typeHandler == null) {
1✔
1156
      typeHandler = typeHandlerRegistry.getTypeHandler(resultMapping.getJavaType(), rsw.getJdbcType(column));
1✔
1157
    }
1158
    return typeHandler.getResult(rsw.getResultSet(), column);
1✔
1159
  }
1160

1161
  private String prependPrefix(String columnName, String prefix) {
1162
    if (columnName == null || columnName.length() == 0 || prefix == null || prefix.length() == 0) {
1!
1163
      return columnName;
1✔
1164
    }
1165
    return prefix + columnName;
1✔
1166
  }
1167

1168
  //
1169
  // HANDLE NESTED RESULT MAPS
1170
  //
1171

1172
  private void handleRowValuesForNestedResultMap(ResultSetWrapper rsw, ResultMap resultMap,
1173
      ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
1174
    final boolean useCollectionConstructorInjection = resultMap.hasResultMapsUsingConstructorCollection();
1✔
1175
    PendingConstructorCreation lastHandledCreation = null;
1✔
1176
    if (useCollectionConstructorInjection) {
1✔
1177
      verifyPendingCreationPreconditions(parentMapping);
1✔
1178
    }
1179

1180
    final DefaultResultContext<Object> resultContext = new DefaultResultContext<>();
1✔
1181
    ResultSet resultSet = rsw.getResultSet();
1✔
1182
    skipRows(resultSet, rowBounds);
1✔
1183
    Object rowValue = previousRowValue;
1✔
1184

1185
    while (shouldProcessMoreRows(resultContext, rowBounds) && !resultSet.isClosed() && resultSet.next()) {
1!
1186
      final ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rsw, resultMap, null);
1✔
1187
      final CacheKey rowKey = createRowKey(discriminatedResultMap, rsw, null);
1✔
1188

1189
      final Object partialObject = nestedResultObjects.get(rowKey);
1✔
1190
      final boolean foundNewUniqueRow = partialObject == null;
1✔
1191

1192
      // issue #577, #542 && #101
1193
      if (useCollectionConstructorInjection) {
1✔
1194
        if (foundNewUniqueRow && lastHandledCreation != null) {
1✔
1195
          createAndStorePendingCreation(resultHandler, resultSet, resultContext, lastHandledCreation);
1✔
1196
          lastHandledCreation = null;
1✔
1197
        }
1198

1199
        rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, null, partialObject);
1✔
1200
        if (rowValue instanceof PendingConstructorCreation) {
1!
1201
          lastHandledCreation = (PendingConstructorCreation) rowValue;
1✔
1202
        }
1203
      } else if (mappedStatement.isResultOrdered()) {
1✔
1204
        if (foundNewUniqueRow && rowValue != null) {
1✔
1205
          nestedResultObjects.clear();
1✔
1206
          storeObject(resultHandler, resultContext, rowValue, parentMapping, resultSet);
1✔
1207
        }
1208
        rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, null, partialObject);
1✔
1209
      } else {
1210
        rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, null, partialObject);
1✔
1211
        if (foundNewUniqueRow) {
1✔
1212
          storeObject(resultHandler, resultContext, rowValue, parentMapping, resultSet);
1✔
1213
        }
1214
      }
1215
    }
1✔
1216

1217
    if (useCollectionConstructorInjection && lastHandledCreation != null) {
1!
1218
      createAndStorePendingCreation(resultHandler, resultSet, resultContext, lastHandledCreation);
1✔
1219
    } else if (rowValue != null && mappedStatement.isResultOrdered()
1✔
1220
        && shouldProcessMoreRows(resultContext, rowBounds)) {
1✔
1221
      storeObject(resultHandler, resultContext, rowValue, parentMapping, resultSet);
1✔
1222
      previousRowValue = null;
1✔
1223
    } else if (rowValue != null) {
1✔
1224
      previousRowValue = rowValue;
1✔
1225
    }
1226
  }
1✔
1227

1228
  //
1229
  // NESTED RESULT MAP (PENDING CONSTRUCTOR CREATIONS)
1230
  //
1231
  private void linkNestedPendingCreations(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix,
1232
      CacheKey parentRowKey, PendingConstructorCreation pendingCreation, List<Object> constructorArgs)
1233
      throws SQLException {
1234
    if (parentRowKey == null) {
1!
1235
      // nothing to link, possibly due to simple (non-nested) result map
1236
      return;
×
1237
    }
1238

1239
    final CacheKey rowKey = createRowKey(resultMap, rsw, columnPrefix);
1✔
1240
    final CacheKey combinedKey = combineKeys(rowKey, parentRowKey);
1✔
1241

1242
    if (combinedKey != CacheKey.NULL_CACHE_KEY) {
1!
1243
      nestedResultObjects.put(combinedKey, pendingCreation);
1✔
1244
    }
1245

1246
    final List<ResultMapping> constructorMappings = resultMap.getConstructorResultMappings();
1✔
1247
    for (int index = 0; index < constructorMappings.size(); index++) {
1✔
1248
      final ResultMapping constructorMapping = constructorMappings.get(index);
1✔
1249
      final String nestedResultMapId = constructorMapping.getNestedResultMapId();
1✔
1250

1251
      if (nestedResultMapId == null) {
1✔
1252
        continue;
1✔
1253
      }
1254

1255
      final Class<?> javaType = constructorMapping.getJavaType();
1✔
1256
      if (javaType == null || !objectFactory.isCollection(javaType)) {
1!
1257
        continue;
1✔
1258
      }
1259

1260
      final String constructorColumnPrefix = getColumnPrefix(columnPrefix, constructorMapping);
1✔
1261
      final ResultMap nestedResultMap = resolveDiscriminatedResultMap(rsw,
1✔
1262
          configuration.getResultMap(constructorMapping.getNestedResultMapId()), constructorColumnPrefix);
1✔
1263

1264
      final Object actualValue = constructorArgs.get(index);
1✔
1265
      final boolean hasValue = actualValue != null;
1✔
1266
      final boolean isInnerCreation = actualValue instanceof PendingConstructorCreation;
1✔
1267
      final boolean alreadyCreatedCollection = hasValue && objectFactory.isCollection(actualValue.getClass());
1!
1268

1269
      if (!isInnerCreation) {
1✔
1270
        final Collection<Object> value = pendingCreation.initializeCollectionForResultMapping(objectFactory,
1✔
1271
            nestedResultMap, constructorMapping, index);
1✔
1272
        if (!alreadyCreatedCollection) {
1!
1273
          // override values with empty collection
1274
          constructorArgs.set(index, value);
1✔
1275
        }
1276

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

1281
        if (nestedCombinedKey != CacheKey.NULL_CACHE_KEY) {
1✔
1282
          nestedResultObjects.put(nestedCombinedKey, pendingCreation);
1✔
1283
        }
1284

1285
        if (hasValue) {
1✔
1286
          pendingCreation.linkCollectionValue(constructorMapping, actualValue);
1✔
1287
        }
1288
      } else {
1✔
1289
        final PendingConstructorCreation innerCreation = (PendingConstructorCreation) actualValue;
1✔
1290
        final Collection<Object> value = pendingCreation.initializeCollectionForResultMapping(objectFactory,
1✔
1291
            nestedResultMap, constructorMapping, index);
1✔
1292
        // we will fill this collection when building the final object
1293
        constructorArgs.set(index, value);
1✔
1294
        // link the creation for building later
1295
        pendingCreation.linkCreation(constructorMapping, innerCreation);
1✔
1296
      }
1297
    }
1298
  }
1✔
1299

1300
  private boolean applyNestedPendingConstructorCreations(ResultSetWrapper rsw, ResultMap resultMap,
1301
      MetaObject metaObject, String parentPrefix, CacheKey parentRowKey, boolean newObject, boolean foundValues) {
1302
    if (newObject) {
1✔
1303
      // new objects are linked by createResultObject
1304
      return false;
1✔
1305
    }
1306

1307
    for (ResultMapping constructorMapping : resultMap.getConstructorResultMappings()) {
1✔
1308
      final String nestedResultMapId = constructorMapping.getNestedResultMapId();
1✔
1309
      final Class<?> parameterType = constructorMapping.getJavaType();
1✔
1310
      if (nestedResultMapId == null || constructorMapping.getResultSet() != null || parameterType == null
1!
1311
          || !objectFactory.isCollection(parameterType)) {
1✔
1312
        continue;
1✔
1313
      }
1314

1315
      try {
1316
        final String columnPrefix = getColumnPrefix(parentPrefix, constructorMapping);
1✔
1317
        final ResultMap nestedResultMap = getNestedResultMap(rsw, nestedResultMapId, columnPrefix);
1✔
1318

1319
        final CacheKey rowKey = createRowKey(nestedResultMap, rsw, columnPrefix);
1✔
1320
        final CacheKey combinedKey = combineKeys(rowKey, parentRowKey);
1✔
1321

1322
        // should have inserted already as a nested result object
1323
        Object rowValue = nestedResultObjects.get(combinedKey);
1✔
1324

1325
        PendingConstructorCreation pendingConstructorCreation = null;
1✔
1326
        if (rowValue instanceof PendingConstructorCreation) {
1✔
1327
          pendingConstructorCreation = (PendingConstructorCreation) rowValue;
1✔
1328
        } else if (rowValue != null) {
1✔
1329
          // found a simple object that was already linked/handled
1330
          continue;
1✔
1331
        }
1332

1333
        final boolean newValueForNestedResultMap = pendingConstructorCreation == null;
1✔
1334
        if (newValueForNestedResultMap) {
1✔
1335
          final Object parentObject = metaObject.getOriginalObject();
1✔
1336
          if (!(parentObject instanceof PendingConstructorCreation)) {
1!
1337
            throw new ExecutorException(
×
1338
                "parentObject is not a pending creation, cannot continue linking! MyBatis internal error!");
1339
          }
1340

1341
          pendingConstructorCreation = (PendingConstructorCreation) parentObject;
1✔
1342
        }
1343

1344
        rowValue = getRowValue(rsw, nestedResultMap, combinedKey, columnPrefix,
1✔
1345
            newValueForNestedResultMap ? null : pendingConstructorCreation);
1✔
1346

1347
        if (rowValue == null) {
1✔
1348
          continue;
1✔
1349
        }
1350

1351
        if (rowValue instanceof PendingConstructorCreation) {
1✔
1352
          if (newValueForNestedResultMap) {
1✔
1353
            // we created a brand new pcc. this is a new collection value
1354
            pendingConstructorCreation.linkCreation(constructorMapping, (PendingConstructorCreation) rowValue);
1✔
1355
            foundValues = true;
1✔
1356
          }
1357
        } else {
1358
          pendingConstructorCreation.linkCollectionValue(constructorMapping, rowValue);
1✔
1359
          foundValues = true;
1✔
1360

1361
          if (combinedKey != CacheKey.NULL_CACHE_KEY) {
1✔
1362
            nestedResultObjects.put(combinedKey, pendingConstructorCreation);
1✔
1363
          }
1364
        }
1365
      } catch (SQLException e) {
×
1366
        throw new ExecutorException("Error getting constructor collection nested result map values for '"
×
1367
            + constructorMapping.getProperty() + "'.  Cause: " + e, e);
×
1368
      }
1✔
1369
    }
1✔
1370

1371
    return foundValues;
1✔
1372
  }
1373

1374
  private void createPendingConstructorCreations(Object rowValue) {
1375
    // handle possible pending creations within this object
1376
    // by now, the property mapping has been completely built, we can reconstruct it
1377
    final PendingRelation pendingRelation = pendingPccRelations.remove(rowValue);
1✔
1378
    final MetaObject metaObject = pendingRelation.metaObject;
1✔
1379
    final ResultMapping resultMapping = pendingRelation.propertyMapping;
1✔
1380

1381
    // get the list to be built
1382
    Object collectionProperty = instantiateCollectionPropertyIfAppropriate(resultMapping, metaObject);
1✔
1383
    if (collectionProperty != null) {
1!
1384
      // we expect pending creations now
1385
      final Collection<Object> pendingCreations = (Collection<Object>) collectionProperty;
1✔
1386

1387
      // remove the link to the old collection
1388
      metaObject.setValue(resultMapping.getProperty(), null);
1✔
1389

1390
      // create new collection property
1391
      collectionProperty = instantiateCollectionPropertyIfAppropriate(resultMapping, metaObject);
1✔
1392
      final MetaObject targetMetaObject = configuration.newMetaObject(collectionProperty);
1✔
1393

1394
      // create the pending objects
1395
      for (Object pendingCreation : pendingCreations) {
1✔
1396
        if (pendingCreation instanceof PendingConstructorCreation) {
1!
1397
          final PendingConstructorCreation pendingConstructorCreation = (PendingConstructorCreation) pendingCreation;
1✔
1398
          targetMetaObject.add(pendingConstructorCreation.create(objectFactory));
1✔
1399
        }
1400
      }
1✔
1401
    }
1402
  }
1✔
1403

1404
  private void verifyPendingCreationPreconditions(ResultMapping parentMapping) {
1405
    if (parentMapping != null) {
1!
1406
      throw new ExecutorException(
×
1407
          "Cannot construct objects with collections in constructors using multiple result sets yet!");
1408
    }
1409

1410
    if (!mappedStatement.isResultOrdered()) {
1!
1411
      throw new ExecutorException("Cannot reliably construct result if we are not sure the results are ordered "
×
1412
          + "so that no new previous rows would occur, set resultOrdered on your mapped statement if you have verified this");
1413
    }
1414
  }
1✔
1415

1416
  private void createAndStorePendingCreation(ResultHandler<?> resultHandler, ResultSet resultSet,
1417
      DefaultResultContext<Object> resultContext, PendingConstructorCreation pendingCreation) throws SQLException {
1418
    final Object result = pendingCreation.create(objectFactory);
1✔
1419
    storeObject(resultHandler, resultContext, result, null, resultSet);
1✔
1420
    nestedResultObjects.clear();
1✔
1421
  }
1✔
1422

1423
  //
1424
  // NESTED RESULT MAP (JOIN MAPPING)
1425
  //
1426

1427
  private boolean applyNestedResultMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject,
1428
      String parentPrefix, CacheKey parentRowKey, boolean newObject) {
1429
    boolean foundValues = false;
1✔
1430
    for (ResultMapping resultMapping : resultMap.getPropertyResultMappings()) {
1✔
1431
      final String nestedResultMapId = resultMapping.getNestedResultMapId();
1✔
1432
      if (nestedResultMapId != null && resultMapping.getResultSet() == null) {
1!
1433
        try {
1434
          final String columnPrefix = getColumnPrefix(parentPrefix, resultMapping);
1✔
1435
          final ResultMap nestedResultMap = getNestedResultMap(rsw, nestedResultMapId, columnPrefix);
1✔
1436
          if (resultMapping.getColumnPrefix() == null) {
1✔
1437
            // try to fill circular reference only when columnPrefix
1438
            // is not specified for the nested result map (issue #215)
1439
            Object ancestorObject = ancestorObjects.get(nestedResultMapId);
1✔
1440
            if (ancestorObject != null) {
1✔
1441
              if (newObject) {
1✔
1442
                linkObjects(metaObject, resultMapping, ancestorObject); // issue #385
1✔
1443
              }
1444
              continue;
1✔
1445
            }
1446
          }
1447
          final CacheKey rowKey = createRowKey(nestedResultMap, rsw, columnPrefix);
1✔
1448
          final CacheKey combinedKey = combineKeys(rowKey, parentRowKey);
1✔
1449
          Object rowValue = nestedResultObjects.get(combinedKey);
1✔
1450
          boolean knownValue = rowValue != null;
1✔
1451
          instantiateCollectionPropertyIfAppropriate(resultMapping, metaObject); // mandatory
1✔
1452
          if (anyNotNullColumnHasValue(resultMapping, columnPrefix, rsw)) {
1✔
1453
            rowValue = getRowValue(rsw, nestedResultMap, combinedKey, columnPrefix, rowValue);
1✔
1454
            if (rowValue != null && !knownValue) {
1✔
1455
              linkObjects(metaObject, resultMapping, rowValue);
1✔
1456
              foundValues = true;
1✔
1457
            }
1458
          }
1459
        } catch (SQLException e) {
×
1460
          throw new ExecutorException(
×
1461
              "Error getting nested result map values for '" + resultMapping.getProperty() + "'.  Cause: " + e, e);
×
1462
        }
1✔
1463
      }
1464
    }
1✔
1465

1466
    // (issue #101)
1467
    if (resultMap.hasResultMapsUsingConstructorCollection()) {
1✔
1468
      foundValues = applyNestedPendingConstructorCreations(rsw, resultMap, metaObject, parentPrefix, parentRowKey,
1✔
1469
          newObject, foundValues);
1470
    }
1471

1472
    return foundValues;
1✔
1473
  }
1474

1475
  private String getColumnPrefix(String parentPrefix, ResultMapping resultMapping) {
1476
    final StringBuilder columnPrefixBuilder = new StringBuilder();
1✔
1477
    if (parentPrefix != null) {
1✔
1478
      columnPrefixBuilder.append(parentPrefix);
1✔
1479
    }
1480
    if (resultMapping.getColumnPrefix() != null) {
1✔
1481
      columnPrefixBuilder.append(resultMapping.getColumnPrefix());
1✔
1482
    }
1483
    return columnPrefixBuilder.length() == 0 ? null : columnPrefixBuilder.toString().toUpperCase(Locale.ENGLISH);
1✔
1484
  }
1485

1486
  private boolean anyNotNullColumnHasValue(ResultMapping resultMapping, String columnPrefix, ResultSetWrapper rsw)
1487
      throws SQLException {
1488
    Set<String> notNullColumns = resultMapping.getNotNullColumns();
1✔
1489
    if (notNullColumns != null && !notNullColumns.isEmpty()) {
1✔
1490
      ResultSet rs = rsw.getResultSet();
1✔
1491
      for (String column : notNullColumns) {
1✔
1492
        rs.getObject(prependPrefix(column, columnPrefix));
1✔
1493
        if (!rs.wasNull()) {
1✔
1494
          return true;
1✔
1495
        }
1496
      }
1✔
1497
      return false;
1✔
1498
    }
1499
    if (columnPrefix != null) {
1✔
1500
      for (String columnName : rsw.getColumnNames()) {
1✔
1501
        if (columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix.toUpperCase(Locale.ENGLISH))) {
1✔
1502
          return true;
1✔
1503
        }
1504
      }
1✔
1505
      return false;
1✔
1506
    }
1507
    return true;
1✔
1508
  }
1509

1510
  private ResultMap getNestedResultMap(ResultSetWrapper rsw, String nestedResultMapId, String columnPrefix)
1511
      throws SQLException {
1512
    ResultMap nestedResultMap = configuration.getResultMap(nestedResultMapId);
1✔
1513
    return resolveDiscriminatedResultMap(rsw, nestedResultMap, columnPrefix);
1✔
1514
  }
1515

1516
  //
1517
  // UNIQUE RESULT KEY
1518
  //
1519

1520
  private CacheKey createRowKey(ResultMap resultMap, ResultSetWrapper rsw, String columnPrefix) throws SQLException {
1521
    final CacheKey cacheKey = new CacheKey();
1✔
1522
    cacheKey.update(resultMap.getId());
1✔
1523
    List<ResultMapping> resultMappings = getResultMappingsForRowKey(resultMap);
1✔
1524
    if (resultMappings.isEmpty()) {
1✔
1525
      if (Map.class.isAssignableFrom(resultMap.getType())) {
1!
1526
        createRowKeyForMap(rsw, cacheKey);
×
1527
      } else {
1528
        createRowKeyForUnmappedProperties(resultMap, rsw, cacheKey, columnPrefix);
1✔
1529
      }
1530
    } else {
1531
      createRowKeyForMappedProperties(resultMap, rsw, cacheKey, resultMappings, columnPrefix);
1✔
1532
    }
1533
    if (cacheKey.getUpdateCount() < 2) {
1✔
1534
      return CacheKey.NULL_CACHE_KEY;
1✔
1535
    }
1536
    return cacheKey;
1✔
1537
  }
1538

1539
  private CacheKey combineKeys(CacheKey rowKey, CacheKey parentRowKey) {
1540
    if (rowKey.getUpdateCount() > 1 && parentRowKey.getUpdateCount() > 1) {
1✔
1541
      CacheKey combinedKey;
1542
      try {
1543
        combinedKey = rowKey.clone();
1✔
1544
      } catch (CloneNotSupportedException e) {
×
1545
        throw new ExecutorException("Error cloning cache key.  Cause: " + e, e);
×
1546
      }
1✔
1547
      combinedKey.update(parentRowKey);
1✔
1548
      return combinedKey;
1✔
1549
    }
1550
    return CacheKey.NULL_CACHE_KEY;
1✔
1551
  }
1552

1553
  private List<ResultMapping> getResultMappingsForRowKey(ResultMap resultMap) {
1554
    List<ResultMapping> resultMappings = resultMap.getIdResultMappings();
1✔
1555
    if (resultMappings.isEmpty()) {
1✔
1556
      resultMappings = resultMap.getPropertyResultMappings();
1✔
1557
    }
1558
    return resultMappings;
1✔
1559
  }
1560

1561
  private void createRowKeyForMappedProperties(ResultMap resultMap, ResultSetWrapper rsw, CacheKey cacheKey,
1562
      List<ResultMapping> resultMappings, String columnPrefix) throws SQLException {
1563
    for (ResultMapping resultMapping : resultMappings) {
1✔
1564
      if (resultMapping.isSimple()) {
1✔
1565
        final String column = prependPrefix(resultMapping.getColumn(), columnPrefix);
1✔
1566
        TypeHandler<?> th = resultMapping.getTypeHandler();
1✔
1567
        Set<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix);
1✔
1568
        // Issue #114
1569
        if (column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH))) {
1!
1570
          if (th == null) {
1✔
1571
            th = typeHandlerRegistry.getTypeHandler(rsw.getJdbcType(column));
1✔
1572
          }
1573
          final Object value = th.getResult(rsw.getResultSet(), column);
1✔
1574
          if (value != null || configuration.isReturnInstanceForEmptyRow()) {
1✔
1575
            cacheKey.update(column);
1✔
1576
            cacheKey.update(value);
1✔
1577
          }
1578
        }
1579
      }
1580
    }
1✔
1581
  }
1✔
1582

1583
  private void createRowKeyForUnmappedProperties(ResultMap resultMap, ResultSetWrapper rsw, CacheKey cacheKey,
1584
      String columnPrefix) throws SQLException {
1585
    final MetaClass metaType = MetaClass.forClass(resultMap.getType(), reflectorFactory);
1✔
1586
    List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
1✔
1587
    for (String column : unmappedColumnNames) {
1✔
1588
      String property = column;
1✔
1589
      if (columnPrefix != null && !columnPrefix.isEmpty()) {
1!
1590
        // When columnPrefix is specified, ignore columns without the prefix.
1591
        if (!column.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
1✔
1592
          continue;
1✔
1593
        }
1594
        property = column.substring(columnPrefix.length());
1✔
1595
      }
1596
      if (metaType.findProperty(property, configuration.isMapUnderscoreToCamelCase()) != null) {
1✔
1597
        String value = rsw.getResultSet().getString(column);
1✔
1598
        if (value != null) {
1✔
1599
          cacheKey.update(column);
1✔
1600
          cacheKey.update(value);
1✔
1601
        }
1602
      }
1603
    }
1✔
1604
  }
1✔
1605

1606
  private void createRowKeyForMap(ResultSetWrapper rsw, CacheKey cacheKey) throws SQLException {
1607
    List<String> columnNames = rsw.getColumnNames();
×
1608
    for (String columnName : columnNames) {
×
1609
      final String value = rsw.getResultSet().getString(columnName);
×
1610
      if (value != null) {
×
1611
        cacheKey.update(columnName);
×
1612
        cacheKey.update(value);
×
1613
      }
1614
    }
×
1615
  }
×
1616

1617
  private void linkObjects(MetaObject metaObject, ResultMapping resultMapping, Object rowValue) {
1618
    linkObjects(metaObject, resultMapping, rowValue, false);
1✔
1619
  }
1✔
1620

1621
  private void linkObjects(MetaObject metaObject, ResultMapping resultMapping, Object rowValue,
1622
      boolean isNestedCursorResult) {
1623
    final Object collectionProperty = instantiateCollectionPropertyIfAppropriate(resultMapping, metaObject);
1✔
1624
    if (collectionProperty != null) {
1✔
1625
      final MetaObject targetMetaObject = configuration.newMetaObject(collectionProperty);
1✔
1626
      if (isNestedCursorResult) {
1!
1627
        targetMetaObject.addAll((List<?>) rowValue);
×
1628
      } else {
1629
        targetMetaObject.add(rowValue);
1✔
1630
      }
1631

1632
      // it is possible for pending creations to get set via property mappings,
1633
      // keep track of these, so we can rebuild them.
1634
      final Object originalObject = metaObject.getOriginalObject();
1✔
1635
      if (rowValue instanceof PendingConstructorCreation && !pendingPccRelations.containsKey(originalObject)) {
1✔
1636
        PendingRelation pendingRelation = new PendingRelation();
1✔
1637
        pendingRelation.propertyMapping = resultMapping;
1✔
1638
        pendingRelation.metaObject = metaObject;
1✔
1639

1640
        pendingPccRelations.put(originalObject, pendingRelation);
1✔
1641
      }
1642
    } else {
1✔
1643
      metaObject.setValue(resultMapping.getProperty(),
1✔
1644
          isNestedCursorResult ? toSingleObj((List<?>) rowValue) : rowValue);
1!
1645
    }
1646
  }
1✔
1647

1648
  private Object toSingleObj(List<?> list) {
1649
    // Even if there are multiple elements, silently returns the first one.
1650
    return list.isEmpty() ? null : list.get(0);
×
1651
  }
1652

1653
  private Object instantiateCollectionPropertyIfAppropriate(ResultMapping resultMapping, MetaObject metaObject) {
1654
    final String propertyName = resultMapping.getProperty();
1✔
1655
    Object propertyValue = metaObject.getValue(propertyName);
1✔
1656
    if (propertyValue == null) {
1✔
1657
      Class<?> type = resultMapping.getJavaType();
1✔
1658
      if (type == null) {
1✔
1659
        type = metaObject.getSetterType(propertyName);
1✔
1660
      }
1661
      try {
1662
        if (objectFactory.isCollection(type)) {
1✔
1663
          propertyValue = objectFactory.create(type);
1✔
1664
          metaObject.setValue(propertyName, propertyValue);
1✔
1665
          return propertyValue;
1✔
1666
        }
1667
      } catch (Exception e) {
×
1668
        throw new ExecutorException(
×
1669
            "Error instantiating collection property for result '" + resultMapping.getProperty() + "'.  Cause: " + e,
×
1670
            e);
1671
      }
1✔
1672
    } else if (objectFactory.isCollection(propertyValue.getClass())) {
1✔
1673
      return propertyValue;
1✔
1674
    }
1675
    return null;
1✔
1676
  }
1677

1678
  private boolean hasTypeHandlerForResultObject(ResultSetWrapper rsw, Class<?> resultType) {
1679
    if (rsw.getColumnNames().size() == 1) {
1✔
1680
      return typeHandlerRegistry.hasTypeHandler(resultType, rsw.getJdbcType(rsw.getColumnNames().get(0)));
1✔
1681
    }
1682
    return typeHandlerRegistry.hasTypeHandler(resultType);
1✔
1683
  }
1684

1685
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc