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

mybatis / mybatis-3 / 2644

07 Jan 2025 10:04AM UTC coverage: 87.27% (-0.02%) from 87.289%
2644

push

github

web-flow
Merge pull request #3391 from harawata/3108-follow-up-type-handler

`resultMap.hasResultMapsUsingConstructorCollection` should stay false if type handler is specified

3615 of 4405 branches covered (82.07%)

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

3 existing lines in 1 file now uncovered.

9550 of 10943 relevant lines covered (87.27%)

0.87 hits per line

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

92.91
/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.sql.CallableStatement;
21
import java.sql.ResultSet;
22
import java.sql.SQLException;
23
import java.sql.Statement;
24
import java.text.MessageFormat;
25
import java.util.ArrayList;
26
import java.util.Arrays;
27
import java.util.Collection;
28
import java.util.HashMap;
29
import java.util.HashSet;
30
import java.util.IdentityHashMap;
31
import java.util.List;
32
import java.util.Locale;
33
import java.util.Map;
34
import java.util.Optional;
35
import java.util.Set;
36

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

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

81
  private static final Object DEFERRED = new Object();
1✔
82

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

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

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

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

106
  // Cached Automappings
107
  private final Map<String, List<UnMappedColumnAutoMapping>> autoMappingsCache = new HashMap<>();
1✔
108
  private final Map<String, List<String>> constructorAutoMappingColumns = new HashMap<>();
1✔
109

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

113
  private static class PendingRelation {
114
    public MetaObject metaObject;
115
    public ResultMapping propertyMapping;
116
  }
117

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

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

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

146
  //
147
  // HANDLE OUTPUT PARAMETER
148
  //
149

150
  @Override
151
  public void handleOutputParameters(CallableStatement cs) throws SQLException {
152
    final Object parameterObject = parameterHandler.getParameterObject();
1✔
153
    final MetaObject metaParam = configuration.newMetaObject(parameterObject);
1✔
154
    final List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
1✔
155
    for (int i = 0; i < parameterMappings.size(); i++) {
1✔
156
      final ParameterMapping parameterMapping = parameterMappings.get(i);
1✔
157
      if (parameterMapping.getMode() == ParameterMode.OUT || parameterMapping.getMode() == ParameterMode.INOUT) {
1!
158
        if (ResultSet.class.equals(parameterMapping.getJavaType())) {
1!
159
          handleRefCursorOutputParameter((ResultSet) cs.getObject(i + 1), parameterMapping, metaParam);
×
160
        } else {
161
          final TypeHandler<?> typeHandler = parameterMapping.getTypeHandler();
1✔
162
          metaParam.setValue(parameterMapping.getProperty(), typeHandler.getResult(cs, i + 1));
1✔
163
        }
164
      }
165
    }
166
  }
1✔
167

168
  private void handleRefCursorOutputParameter(ResultSet rs, ParameterMapping parameterMapping, MetaObject metaParam)
169
      throws SQLException {
170
    if (rs == null) {
×
171
      return;
×
172
    }
173
    try {
174
      final String resultMapId = parameterMapping.getResultMapId();
×
175
      final ResultMap resultMap = configuration.getResultMap(resultMapId);
×
176
      final ResultSetWrapper rsw = new ResultSetWrapper(rs, configuration);
×
177
      if (this.resultHandler == null) {
×
178
        final DefaultResultHandler resultHandler = new DefaultResultHandler(objectFactory);
×
179
        handleRowValues(rsw, resultMap, resultHandler, new RowBounds(), null);
×
180
        metaParam.setValue(parameterMapping.getProperty(), resultHandler.getResultList());
×
181
      } else {
×
182
        handleRowValues(rsw, resultMap, resultHandler, new RowBounds(), null);
×
183
      }
184
    } finally {
185
      // issue #228 (close resultsets)
186
      closeResultSet(rs);
×
187
    }
188
  }
×
189

190
  //
191
  // HANDLE RESULT SETS
192
  //
193
  @Override
194
  public List<Object> handleResultSets(Statement stmt) throws SQLException {
195
    ErrorContext.instance().activity("handling results").object(mappedStatement.getId());
1✔
196

197
    final List<Object> multipleResults = new ArrayList<>();
1✔
198

199
    int resultSetCount = 0;
1✔
200
    ResultSetWrapper rsw = getFirstResultSet(stmt);
1✔
201

202
    List<ResultMap> resultMaps = mappedStatement.getResultMaps();
1✔
203
    int resultMapCount = resultMaps.size();
1✔
204
    validateResultMapsCount(rsw, resultMapCount);
1✔
205
    while (rsw != null && resultMapCount > resultSetCount) {
1✔
206
      ResultMap resultMap = resultMaps.get(resultSetCount);
1✔
207
      handleResultSet(rsw, resultMap, multipleResults, null);
1✔
208
      rsw = getNextResultSet(stmt);
1✔
209
      cleanUpAfterHandlingResultSet();
1✔
210
      resultSetCount++;
1✔
211
    }
1✔
212

213
    String[] resultSets = mappedStatement.getResultSets();
1✔
214
    if (resultSets != null) {
1✔
215
      while (rsw != null && resultSetCount < resultSets.length) {
1!
216
        ResultMapping parentMapping = nextResultMaps.get(resultSets[resultSetCount]);
1✔
217
        if (parentMapping != null) {
1!
218
          String nestedResultMapId = parentMapping.getNestedResultMapId();
1✔
219
          ResultMap resultMap = configuration.getResultMap(nestedResultMapId);
1✔
220
          handleResultSet(rsw, resultMap, null, parentMapping);
1✔
221
        }
222
        rsw = getNextResultSet(stmt);
1✔
223
        cleanUpAfterHandlingResultSet();
1✔
224
        resultSetCount++;
1✔
225
      }
1✔
226
    }
227

228
    return collapseSingleResultList(multipleResults);
1✔
229
  }
230

231
  @Override
232
  public <E> Cursor<E> handleCursorResultSets(Statement stmt) throws SQLException {
233
    ErrorContext.instance().activity("handling cursor results").object(mappedStatement.getId());
1✔
234

235
    ResultSetWrapper rsw = getFirstResultSet(stmt);
1✔
236

237
    List<ResultMap> resultMaps = mappedStatement.getResultMaps();
1✔
238

239
    int resultMapCount = resultMaps.size();
1✔
240
    validateResultMapsCount(rsw, resultMapCount);
1✔
241
    if (resultMapCount != 1) {
1!
242
      throw new ExecutorException("Cursor results cannot be mapped to multiple resultMaps");
×
243
    }
244

245
    ResultMap resultMap = resultMaps.get(0);
1✔
246
    return new DefaultCursor<>(this, resultMap, rsw, rowBounds);
1✔
247
  }
248

249
  private ResultSetWrapper getFirstResultSet(Statement stmt) throws SQLException {
250
    ResultSet rs = null;
1✔
251
    SQLException e1 = null;
1✔
252

253
    try {
254
      rs = stmt.getResultSet();
1✔
255
    } catch (SQLException e) {
×
256
      // Oracle throws ORA-17283 for implicit cursor
257
      e1 = e;
×
258
    }
1✔
259

260
    try {
261
      while (rs == null) {
1✔
262
        // move forward to get the first resultset in case the driver
263
        // doesn't return the resultset as the first result (HSQLDB)
264
        if (stmt.getMoreResults()) {
1!
265
          rs = stmt.getResultSet();
×
266
        } else if (stmt.getUpdateCount() == -1) {
1!
267
          // no more results. Must be no resultset
268
          break;
1✔
269
        }
270
      }
271
    } catch (SQLException e) {
×
272
      throw e1 != null ? e1 : e;
×
273
    }
1✔
274

275
    return rs != null ? new ResultSetWrapper(rs, configuration) : null;
1✔
276
  }
277

278
  private ResultSetWrapper getNextResultSet(Statement stmt) {
279
    // Making this method tolerant of bad JDBC drivers
280
    try {
281
      // We stopped checking DatabaseMetaData#supportsMultipleResultSets()
282
      // because Oracle driver (incorrectly) returns false
283

284
      // Crazy Standard JDBC way of determining if there are more results
285
      // DO NOT try to 'improve' the condition even if IDE tells you to!
286
      // It's important that getUpdateCount() is called here.
287
      if (!(!stmt.getMoreResults() && stmt.getUpdateCount() == -1)) {
1✔
288
        ResultSet rs = stmt.getResultSet();
1✔
289
        if (rs == null) {
1!
290
          return getNextResultSet(stmt);
×
291
        } else {
292
          return new ResultSetWrapper(rs, configuration);
1✔
293
        }
294
      }
295
    } catch (Exception e) {
×
296
      // Intentionally ignored.
297
    }
1✔
298
    return null;
1✔
299
  }
300

301
  private void closeResultSet(ResultSet rs) {
302
    try {
303
      if (rs != null) {
1!
304
        rs.close();
1✔
305
      }
306
    } catch (SQLException e) {
×
307
      // ignore
308
    }
1✔
309
  }
1✔
310

311
  private void cleanUpAfterHandlingResultSet() {
312
    nestedResultObjects.clear();
1✔
313
  }
1✔
314

315
  private void validateResultMapsCount(ResultSetWrapper rsw, int resultMapCount) {
316
    if (rsw != null && resultMapCount < 1) {
1✔
317
      throw new ExecutorException(
1✔
318
          "A query was run and no Result Maps were found for the Mapped Statement '" + mappedStatement.getId()
1✔
319
              + "'. 'resultType' or 'resultMap' must be specified when there is no corresponding method.");
320
    }
321
  }
1✔
322

323
  private void handleResultSet(ResultSetWrapper rsw, ResultMap resultMap, List<Object> multipleResults,
324
      ResultMapping parentMapping) throws SQLException {
325
    try {
326
      if (parentMapping != null) {
1✔
327
        handleRowValues(rsw, resultMap, null, RowBounds.DEFAULT, parentMapping);
1✔
328
      } else if (resultHandler == null) {
1✔
329
        DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory);
1✔
330
        handleRowValues(rsw, resultMap, defaultResultHandler, rowBounds, null);
1✔
331
        multipleResults.add(defaultResultHandler.getResultList());
1✔
332
      } else {
1✔
333
        handleRowValues(rsw, resultMap, resultHandler, rowBounds, null);
1✔
334
      }
335
    } finally {
336
      // issue #228 (close resultsets)
337
      closeResultSet(rsw.getResultSet());
1✔
338
    }
339
  }
1✔
340

341
  @SuppressWarnings("unchecked")
342
  private List<Object> collapseSingleResultList(List<Object> multipleResults) {
343
    return multipleResults.size() == 1 ? (List<Object>) multipleResults.get(0) : multipleResults;
1✔
344
  }
345

346
  //
347
  // HANDLE ROWS FOR SIMPLE RESULTMAP
348
  //
349

350
  public void handleRowValues(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler,
351
      RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
352
    if (resultMap.hasNestedResultMaps()) {
1✔
353
      ensureNoRowBounds();
1✔
354
      checkResultHandler();
1✔
355
      handleRowValuesForNestedResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
1✔
356
    } else {
357
      handleRowValuesForSimpleResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
1✔
358
    }
359
  }
1✔
360

361
  private void ensureNoRowBounds() {
362
    if (configuration.isSafeRowBoundsEnabled() && rowBounds != null
1!
363
        && (rowBounds.getLimit() < RowBounds.NO_ROW_LIMIT || rowBounds.getOffset() > RowBounds.NO_ROW_OFFSET)) {
×
364
      throw new ExecutorException(
×
365
          "Mapped Statements with nested result mappings cannot be safely constrained by RowBounds. "
366
              + "Use safeRowBoundsEnabled=false setting to bypass this check.");
367
    }
368
  }
1✔
369

370
  protected void checkResultHandler() {
371
    if (resultHandler != null && configuration.isSafeResultHandlerEnabled() && !mappedStatement.isResultOrdered()) {
1!
372
      throw new ExecutorException(
1✔
373
          "Mapped Statements with nested result mappings cannot be safely used with a custom ResultHandler. "
374
              + "Use safeResultHandlerEnabled=false setting to bypass this check "
375
              + "or ensure your statement returns ordered data and set resultOrdered=true on it.");
376
    }
377
  }
1✔
378

379
  private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap,
380
      ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
381
    final boolean useCollectionConstructorInjection = resultMap.hasResultMapsUsingConstructorCollection();
1✔
382

383
    DefaultResultContext<Object> resultContext = new DefaultResultContext<>();
1✔
384
    ResultSet resultSet = rsw.getResultSet();
1✔
385
    skipRows(resultSet, rowBounds);
1✔
386
    while (shouldProcessMoreRows(resultContext, rowBounds) && !resultSet.isClosed() && resultSet.next()) {
1!
387
      ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(resultSet, resultMap, null);
1✔
388
      Object rowValue = getRowValue(rsw, discriminatedResultMap, null, null);
1✔
389
      if (!useCollectionConstructorInjection) {
1!
390
        storeObject(resultHandler, resultContext, rowValue, parentMapping, resultSet);
1✔
391
      } else {
UNCOV
392
        if (!(rowValue instanceof PendingConstructorCreation)) {
×
393
          throw new ExecutorException("Expected result object to be a pending constructor creation!");
×
394
        }
395

UNCOV
396
        createAndStorePendingCreation(resultHandler, resultSet, resultContext, (PendingConstructorCreation) rowValue);
×
397
      }
398
    }
1✔
399
  }
1✔
400

401
  private void storeObject(ResultHandler<?> resultHandler, DefaultResultContext<Object> resultContext, Object rowValue,
402
      ResultMapping parentMapping, ResultSet rs) throws SQLException {
403
    if (parentMapping != null) {
1✔
404
      linkToParents(rs, parentMapping, rowValue);
1✔
405
      return;
1✔
406
    }
407

408
    if (pendingPccRelations.containsKey(rowValue)) {
1✔
409
      createPendingConstructorCreations(rowValue);
1✔
410
    }
411

412
    callResultHandler(resultHandler, resultContext, rowValue);
1✔
413
  }
1✔
414

415
  @SuppressWarnings("unchecked" /* because ResultHandler<?> is always ResultHandler<Object> */)
416
  private void callResultHandler(ResultHandler<?> resultHandler, DefaultResultContext<Object> resultContext,
417
      Object rowValue) {
418
    resultContext.nextResultObject(rowValue);
1✔
419
    ((ResultHandler<Object>) resultHandler).handleResult(resultContext);
1✔
420
  }
1✔
421

422
  private boolean shouldProcessMoreRows(ResultContext<?> context, RowBounds rowBounds) {
423
    return !context.isStopped() && context.getResultCount() < rowBounds.getLimit();
1✔
424
  }
425

426
  private void skipRows(ResultSet rs, RowBounds rowBounds) throws SQLException {
427
    if (rs.getType() != ResultSet.TYPE_FORWARD_ONLY) {
1✔
428
      if (rowBounds.getOffset() != RowBounds.NO_ROW_OFFSET) {
1!
429
        rs.absolute(rowBounds.getOffset());
1✔
430
      }
431
    } else {
432
      for (int i = 0; i < rowBounds.getOffset(); i++) {
1✔
433
        if (!rs.next()) {
1!
434
          break;
×
435
        }
436
      }
437
    }
438
  }
1✔
439

440
  //
441
  // GET VALUE FROM ROW FOR SIMPLE RESULT MAP
442
  //
443

444
  private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix, CacheKey parentRowKey)
445
      throws SQLException {
446
    final ResultLoaderMap lazyLoader = new ResultLoaderMap();
1✔
447
    Object rowValue = createResultObject(rsw, resultMap, lazyLoader, columnPrefix, parentRowKey);
1✔
448
    if (rowValue != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
1✔
449
      final MetaObject metaObject = configuration.newMetaObject(rowValue);
1✔
450
      boolean foundValues = this.useConstructorMappings;
1✔
451
      if (shouldApplyAutomaticMappings(resultMap, false)) {
1✔
452
        foundValues = applyAutomaticMappings(rsw, resultMap, metaObject, columnPrefix) || foundValues;
1✔
453
      }
454
      foundValues = applyPropertyMappings(rsw, resultMap, metaObject, lazyLoader, columnPrefix) || foundValues;
1✔
455
      foundValues = lazyLoader.size() > 0 || foundValues;
1✔
456
      rowValue = foundValues || configuration.isReturnInstanceForEmptyRow() ? rowValue : null;
1✔
457
    }
458

459
    if (parentRowKey != null) {
1✔
460
      // found a simple object/primitive in pending constructor creation that will need linking later
461
      final CacheKey rowKey = createRowKey(resultMap, rsw, columnPrefix);
1✔
462
      final CacheKey combinedKey = combineKeys(rowKey, parentRowKey);
1✔
463

464
      if (combinedKey != CacheKey.NULL_CACHE_KEY) {
1✔
465
        nestedResultObjects.put(combinedKey, rowValue);
1✔
466
      }
467
    }
468

469
    return rowValue;
1✔
470
  }
471

472
  //
473
  // GET VALUE FROM ROW FOR NESTED RESULT MAP
474
  //
475

476
  private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap, CacheKey combinedKey, String columnPrefix,
477
      Object partialObject) throws SQLException {
478
    final String resultMapId = resultMap.getId();
1✔
479
    Object rowValue = partialObject;
1✔
480
    if (rowValue != null) {
1✔
481
      final MetaObject metaObject = configuration.newMetaObject(rowValue);
1✔
482
      putAncestor(rowValue, resultMapId);
1✔
483
      applyNestedResultMappings(rsw, resultMap, metaObject, columnPrefix, combinedKey, false);
1✔
484
      ancestorObjects.remove(resultMapId);
1✔
485
    } else {
1✔
486
      final ResultLoaderMap lazyLoader = new ResultLoaderMap();
1✔
487
      rowValue = createResultObject(rsw, resultMap, lazyLoader, columnPrefix, combinedKey);
1✔
488
      if (rowValue != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
1✔
489
        final MetaObject metaObject = configuration.newMetaObject(rowValue);
1✔
490
        boolean foundValues = this.useConstructorMappings;
1✔
491
        if (shouldApplyAutomaticMappings(resultMap, true)) {
1✔
492
          foundValues = applyAutomaticMappings(rsw, resultMap, metaObject, columnPrefix) || foundValues;
1!
493
        }
494
        foundValues = applyPropertyMappings(rsw, resultMap, metaObject, lazyLoader, columnPrefix) || foundValues;
1✔
495
        putAncestor(rowValue, resultMapId);
1✔
496
        foundValues = applyNestedResultMappings(rsw, resultMap, metaObject, columnPrefix, combinedKey, true)
1✔
497
            || foundValues;
498
        ancestorObjects.remove(resultMapId);
1✔
499
        foundValues = lazyLoader.size() > 0 || foundValues;
1✔
500
        rowValue = foundValues || configuration.isReturnInstanceForEmptyRow() ? rowValue : null;
1✔
501
      }
502
      if (combinedKey != CacheKey.NULL_CACHE_KEY) {
1✔
503
        nestedResultObjects.put(combinedKey, rowValue);
1✔
504
      }
505
    }
506
    return rowValue;
1✔
507
  }
508

509
  private void putAncestor(Object resultObject, String resultMapId) {
510
    ancestorObjects.put(resultMapId, resultObject);
1✔
511
  }
1✔
512

513
  private boolean shouldApplyAutomaticMappings(ResultMap resultMap, boolean isNested) {
514
    if (resultMap.getAutoMapping() != null) {
1✔
515
      return resultMap.getAutoMapping();
1✔
516
    }
517
    if (isNested) {
1✔
518
      return AutoMappingBehavior.FULL == configuration.getAutoMappingBehavior();
1✔
519
    } else {
520
      return AutoMappingBehavior.NONE != configuration.getAutoMappingBehavior();
1✔
521
    }
522
  }
523

524
  //
525
  // PROPERTY MAPPINGS
526
  //
527

528
  private boolean applyPropertyMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject,
529
      ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException {
530
    final Set<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix);
1✔
531
    boolean foundValues = false;
1✔
532
    final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings();
1✔
533
    for (ResultMapping propertyMapping : propertyMappings) {
1✔
534
      String column = prependPrefix(propertyMapping.getColumn(), columnPrefix);
1✔
535
      if (propertyMapping.getNestedResultMapId() != null) {
1✔
536
        // the user added a column attribute to a nested result map, ignore it
537
        column = null;
1✔
538
      }
539
      if (propertyMapping.isCompositeResult()
1✔
540
          || column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH))
1✔
541
          || propertyMapping.getResultSet() != null) {
1✔
542
        Object value = getPropertyMappingValue(rsw.getResultSet(), metaObject, propertyMapping, lazyLoader,
1✔
543
            columnPrefix);
544
        // issue #541 make property optional
545
        final String property = propertyMapping.getProperty();
1✔
546
        if (property == null) {
1✔
547
          continue;
1✔
548
        }
549
        if (value == DEFERRED) {
1✔
550
          foundValues = true;
1✔
551
          continue;
1✔
552
        }
553
        if (value != null) {
1✔
554
          foundValues = true;
1✔
555
        }
556
        if (value != null
1✔
557
            || configuration.isCallSettersOnNulls() && !metaObject.getSetterType(property).isPrimitive()) {
1!
558
          // gcode issue #377, call setter on nulls (value is not 'found')
559
          metaObject.setValue(property, value);
1✔
560
        }
561
      }
562
    }
1✔
563
    return foundValues;
1✔
564
  }
565

566
  private Object getPropertyMappingValue(ResultSet rs, MetaObject metaResultObject, ResultMapping propertyMapping,
567
      ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException {
568
    if (propertyMapping.getNestedQueryId() != null) {
1✔
569
      return getNestedQueryMappingValue(rs, metaResultObject, propertyMapping, lazyLoader, columnPrefix);
1✔
570
    }
571
    if (propertyMapping.getResultSet() != null) {
1✔
572
      addPendingChildRelation(rs, metaResultObject, propertyMapping); // TODO is that OK?
1✔
573
      return DEFERRED;
1✔
574
    } else {
575
      final TypeHandler<?> typeHandler = propertyMapping.getTypeHandler();
1✔
576
      final String column = prependPrefix(propertyMapping.getColumn(), columnPrefix);
1✔
577
      return typeHandler.getResult(rs, column);
1✔
578
    }
579
  }
580

581
  private List<UnMappedColumnAutoMapping> createAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap,
582
      MetaObject metaObject, String columnPrefix) throws SQLException {
583
    final String mapKey = resultMap.getId() + ":" + columnPrefix;
1✔
584
    List<UnMappedColumnAutoMapping> autoMapping = autoMappingsCache.get(mapKey);
1✔
585
    if (autoMapping == null) {
1✔
586
      autoMapping = new ArrayList<>();
1✔
587
      final List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
1✔
588
      // Remove the entry to release the memory
589
      List<String> mappedInConstructorAutoMapping = constructorAutoMappingColumns.remove(mapKey);
1✔
590
      if (mappedInConstructorAutoMapping != null) {
1✔
591
        unmappedColumnNames.removeAll(mappedInConstructorAutoMapping);
1✔
592
      }
593
      for (String columnName : unmappedColumnNames) {
1✔
594
        String propertyName = columnName;
1✔
595
        if (columnPrefix != null && !columnPrefix.isEmpty()) {
1!
596
          // When columnPrefix is specified,
597
          // ignore columns without the prefix.
598
          if (!columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
1✔
599
            continue;
1✔
600
          }
601
          propertyName = columnName.substring(columnPrefix.length());
1✔
602
        }
603
        final String property = metaObject.findProperty(propertyName, configuration.isMapUnderscoreToCamelCase());
1✔
604
        if (property != null && metaObject.hasSetter(property)) {
1✔
605
          if (resultMap.getMappedProperties().contains(property)) {
1✔
606
            continue;
1✔
607
          }
608
          final Class<?> propertyType = metaObject.getSetterType(property);
1✔
609
          if (typeHandlerRegistry.hasTypeHandler(propertyType, rsw.getJdbcType(columnName))) {
1✔
610
            final TypeHandler<?> typeHandler = rsw.getTypeHandler(propertyType, columnName);
1✔
611
            autoMapping
1✔
612
                .add(new UnMappedColumnAutoMapping(columnName, property, typeHandler, propertyType.isPrimitive()));
1✔
613
          } else {
1✔
614
            configuration.getAutoMappingUnknownColumnBehavior().doAction(mappedStatement, columnName, property,
1✔
615
                propertyType);
616
          }
617
        } else {
1✔
618
          configuration.getAutoMappingUnknownColumnBehavior().doAction(mappedStatement, columnName,
1✔
619
              property != null ? property : propertyName, null);
1✔
620
        }
621
      }
1✔
622
      autoMappingsCache.put(mapKey, autoMapping);
1✔
623
    }
624
    return autoMapping;
1✔
625
  }
626

627
  private boolean applyAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject,
628
      String columnPrefix) throws SQLException {
629
    List<UnMappedColumnAutoMapping> autoMapping = createAutomaticMappings(rsw, resultMap, metaObject, columnPrefix);
1✔
630
    boolean foundValues = false;
1✔
631
    if (!autoMapping.isEmpty()) {
1✔
632
      for (UnMappedColumnAutoMapping mapping : autoMapping) {
1✔
633
        final Object value = mapping.typeHandler.getResult(rsw.getResultSet(), mapping.column);
1✔
634
        if (value != null) {
1✔
635
          foundValues = true;
1✔
636
        }
637
        if (value != null || configuration.isCallSettersOnNulls() && !mapping.primitive) {
1!
638
          // gcode issue #377, call setter on nulls (value is not 'found')
639
          metaObject.setValue(mapping.property, value);
1✔
640
        }
641
      }
1✔
642
    }
643
    return foundValues;
1✔
644
  }
645

646
  // MULTIPLE RESULT SETS
647

648
  private void linkToParents(ResultSet rs, ResultMapping parentMapping, Object rowValue) throws SQLException {
649
    CacheKey parentKey = createKeyForMultipleResults(rs, parentMapping, parentMapping.getColumn(),
1✔
650
        parentMapping.getForeignColumn());
1✔
651
    List<PendingRelation> parents = pendingRelations.get(parentKey);
1✔
652
    if (parents != null) {
1✔
653
      for (PendingRelation parent : parents) {
1✔
654
        if (parent != null && rowValue != null) {
1!
655
          linkObjects(parent.metaObject, parent.propertyMapping, rowValue);
1✔
656
        }
657
      }
1✔
658
    }
659
  }
1✔
660

661
  private void addPendingChildRelation(ResultSet rs, MetaObject metaResultObject, ResultMapping parentMapping)
662
      throws SQLException {
663
    CacheKey cacheKey = createKeyForMultipleResults(rs, parentMapping, parentMapping.getColumn(),
1✔
664
        parentMapping.getColumn());
1✔
665
    PendingRelation deferLoad = new PendingRelation();
1✔
666
    deferLoad.metaObject = metaResultObject;
1✔
667
    deferLoad.propertyMapping = parentMapping;
1✔
668
    List<PendingRelation> relations = pendingRelations.computeIfAbsent(cacheKey, k -> new ArrayList<>());
1✔
669
    // issue #255
670
    relations.add(deferLoad);
1✔
671
    ResultMapping previous = nextResultMaps.get(parentMapping.getResultSet());
1✔
672
    if (previous == null) {
1✔
673
      nextResultMaps.put(parentMapping.getResultSet(), parentMapping);
1✔
674
    } else if (!previous.equals(parentMapping)) {
1!
675
      throw new ExecutorException("Two different properties are mapped to the same resultSet");
×
676
    }
677
  }
1✔
678

679
  private CacheKey createKeyForMultipleResults(ResultSet rs, ResultMapping resultMapping, String names, String columns)
680
      throws SQLException {
681
    CacheKey cacheKey = new CacheKey();
1✔
682
    cacheKey.update(resultMapping);
1✔
683
    if (columns != null && names != null) {
1!
684
      String[] columnsArray = columns.split(",");
1✔
685
      String[] namesArray = names.split(",");
1✔
686
      for (int i = 0; i < columnsArray.length; i++) {
1✔
687
        Object value = rs.getString(columnsArray[i]);
1✔
688
        if (value != null) {
1!
689
          cacheKey.update(namesArray[i]);
1✔
690
          cacheKey.update(value);
1✔
691
        }
692
      }
693
    }
694
    return cacheKey;
1✔
695
  }
696

697
  //
698
  // INSTANTIATION & CONSTRUCTOR MAPPING
699
  //
700

701
  private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, ResultLoaderMap lazyLoader,
702
      String columnPrefix, CacheKey parentRowKey) throws SQLException {
703
    this.useConstructorMappings = false; // reset previous mapping result
1✔
704
    final List<Class<?>> constructorArgTypes = new ArrayList<>();
1✔
705
    final List<Object> constructorArgs = new ArrayList<>();
1✔
706

707
    Object resultObject = createResultObject(rsw, resultMap, constructorArgTypes, constructorArgs, columnPrefix,
1✔
708
        parentRowKey);
709
    if (resultObject != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
1✔
710
      final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings();
1✔
711
      for (ResultMapping propertyMapping : propertyMappings) {
1✔
712
        // issue gcode #109 && issue #149
713
        if (propertyMapping.getNestedQueryId() != null && propertyMapping.isLazy()) {
1✔
714
          resultObject = configuration.getProxyFactory().createProxy(resultObject, lazyLoader, configuration,
1✔
715
              objectFactory, constructorArgTypes, constructorArgs);
716
          break;
1✔
717
        }
718
      }
1✔
719

720
      // (issue #101)
721
      if (resultMap.hasResultMapsUsingConstructorCollection() && resultObject instanceof PendingConstructorCreation) {
1!
722
        linkNestedPendingCreations(rsw, resultMap, columnPrefix, parentRowKey,
1✔
723
            (PendingConstructorCreation) resultObject, constructorArgs);
724
      }
725
    }
726

727
    this.useConstructorMappings = resultObject != null && !constructorArgTypes.isEmpty(); // set current mapping result
1✔
728
    return resultObject;
1✔
729
  }
730

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

734
    final Class<?> resultType = resultMap.getType();
1✔
735
    final MetaClass metaType = MetaClass.forClass(resultType, reflectorFactory);
1✔
736
    final List<ResultMapping> constructorMappings = resultMap.getConstructorResultMappings();
1✔
737
    if (hasTypeHandlerForResultObject(rsw, resultType)) {
1✔
738
      return createPrimitiveResultObject(rsw, resultMap, columnPrefix);
1✔
739
    }
740
    if (!constructorMappings.isEmpty()) {
1✔
741
      return createParameterizedResultObject(rsw, resultType, constructorMappings, constructorArgTypes, constructorArgs,
1✔
742
          columnPrefix, resultMap.hasResultMapsUsingConstructorCollection(), parentRowKey);
1✔
743
    } else if (resultType.isInterface() || metaType.hasDefaultConstructor()) {
1✔
744
      return objectFactory.create(resultType);
1✔
745
    } else if (shouldApplyAutomaticMappings(resultMap, false)) {
1!
746
      return createByConstructorSignature(rsw, resultMap, columnPrefix, resultType, constructorArgTypes,
1✔
747
          constructorArgs);
748
    }
749
    throw new ExecutorException("Do not know how to create an instance of " + resultType);
×
750
  }
751

752
  Object createParameterizedResultObject(ResultSetWrapper rsw, Class<?> resultType,
753
      List<ResultMapping> constructorMappings, List<Class<?>> constructorArgTypes, List<Object> constructorArgs,
754
      String columnPrefix, boolean useCollectionConstructorInjection, CacheKey parentRowKey) {
755
    boolean foundValues = false;
1✔
756

757
    for (ResultMapping constructorMapping : constructorMappings) {
1✔
758
      final Class<?> parameterType = constructorMapping.getJavaType();
1✔
759
      final String column = constructorMapping.getColumn();
1✔
760
      final Object value;
761
      try {
762
        if (constructorMapping.getNestedQueryId() != null) {
1✔
763
          value = getNestedQueryConstructorValue(rsw.getResultSet(), constructorMapping, columnPrefix);
1✔
764
        } else if (constructorMapping.getNestedResultMapId() != null) {
1✔
765
          final String constructorColumnPrefix = getColumnPrefix(columnPrefix, constructorMapping);
1✔
766
          final ResultMap resultMap = resolveDiscriminatedResultMap(rsw.getResultSet(),
1✔
767
              configuration.getResultMap(constructorMapping.getNestedResultMapId()), constructorColumnPrefix);
1✔
768
          value = getRowValue(rsw, resultMap, constructorColumnPrefix,
1✔
769
              useCollectionConstructorInjection ? parentRowKey : null);
1✔
770
        } else {
1✔
771
          final TypeHandler<?> typeHandler = constructorMapping.getTypeHandler();
1✔
772
          value = typeHandler.getResult(rsw.getResultSet(), prependPrefix(column, columnPrefix));
1✔
773
        }
774
      } catch (ResultMapException | SQLException e) {
1✔
775
        throw new ExecutorException("Could not process result for mapping: " + constructorMapping, e);
1✔
776
      }
1✔
777

778
      constructorArgTypes.add(parameterType);
1✔
779
      constructorArgs.add(value);
1✔
780

781
      foundValues = value != null || foundValues;
1✔
782
    }
1✔
783

784
    if (!foundValues) {
1✔
785
      return null;
1✔
786
    }
787

788
    if (useCollectionConstructorInjection) {
1✔
789
      // at least one of the nestedResultMaps contained a collection, we have to defer until later
790
      return new PendingConstructorCreation(resultType, constructorArgTypes, constructorArgs);
1✔
791
    }
792

793
    return objectFactory.create(resultType, constructorArgTypes, constructorArgs);
1✔
794
  }
795

796
  private Object createByConstructorSignature(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix,
797
      Class<?> resultType, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) throws SQLException {
798
    return applyConstructorAutomapping(rsw, resultMap, columnPrefix, resultType, constructorArgTypes, constructorArgs,
1✔
799
        findConstructorForAutomapping(resultType, rsw).orElseThrow(() -> new ExecutorException(
1✔
800
            "No constructor found in " + resultType.getName() + " matching " + rsw.getClassNames())));
×
801
  }
802

803
  private Optional<Constructor<?>> findConstructorForAutomapping(final Class<?> resultType, ResultSetWrapper rsw) {
804
    Constructor<?>[] constructors = resultType.getDeclaredConstructors();
1✔
805
    if (constructors.length == 1) {
1✔
806
      return Optional.of(constructors[0]);
1✔
807
    }
808
    Optional<Constructor<?>> annotated = Arrays.stream(constructors)
1✔
809
        .filter(x -> x.isAnnotationPresent(AutomapConstructor.class)).reduce((x, y) -> {
1✔
810
          throw new ExecutorException("@AutomapConstructor should be used in only one constructor.");
1✔
811
        });
812
    if (annotated.isPresent()) {
1✔
813
      return annotated;
1✔
814
    }
815
    if (configuration.isArgNameBasedConstructorAutoMapping()) {
1!
816
      // Finding-best-match type implementation is possible,
817
      // but using @AutomapConstructor seems sufficient.
818
      throw new ExecutorException(MessageFormat.format(
×
819
          "'argNameBasedConstructorAutoMapping' is enabled and the class ''{0}'' has multiple constructors, so @AutomapConstructor must be added to one of the constructors.",
820
          resultType.getName()));
×
821
    } else {
822
      return Arrays.stream(constructors).filter(x -> findUsableConstructorByArgTypes(x, rsw.getJdbcTypes())).findAny();
1✔
823
    }
824
  }
825

826
  private boolean findUsableConstructorByArgTypes(final Constructor<?> constructor, final List<JdbcType> jdbcTypes) {
827
    final Class<?>[] parameterTypes = constructor.getParameterTypes();
1✔
828
    if (parameterTypes.length != jdbcTypes.size()) {
1✔
829
      return false;
1✔
830
    }
831
    for (int i = 0; i < parameterTypes.length; i++) {
1✔
832
      if (!typeHandlerRegistry.hasTypeHandler(parameterTypes[i], jdbcTypes.get(i))) {
1!
833
        return false;
×
834
      }
835
    }
836
    return true;
1✔
837
  }
838

839
  private Object applyConstructorAutomapping(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix,
840
      Class<?> resultType, List<Class<?>> constructorArgTypes, List<Object> constructorArgs, Constructor<?> constructor)
841
      throws SQLException {
842
    boolean foundValues = false;
1✔
843
    if (configuration.isArgNameBasedConstructorAutoMapping()) {
1✔
844
      foundValues = applyArgNameBasedConstructorAutoMapping(rsw, resultMap, columnPrefix, constructorArgTypes,
1✔
845
          constructorArgs, constructor, foundValues);
846
    } else {
847
      foundValues = applyColumnOrderBasedConstructorAutomapping(rsw, constructorArgTypes, constructorArgs, constructor,
1✔
848
          foundValues);
849
    }
850
    return foundValues || configuration.isReturnInstanceForEmptyRow()
1!
851
        ? objectFactory.create(resultType, constructorArgTypes, constructorArgs) : null;
1✔
852
  }
853

854
  private boolean applyColumnOrderBasedConstructorAutomapping(ResultSetWrapper rsw, List<Class<?>> constructorArgTypes,
855
      List<Object> constructorArgs, Constructor<?> constructor, boolean foundValues) throws SQLException {
856
    Class<?>[] parameterTypes = constructor.getParameterTypes();
1✔
857

858
    if (parameterTypes.length > rsw.getClassNames().size()) {
1✔
859
      throw new ExecutorException(MessageFormat.format(
1✔
860
          "Constructor auto-mapping of ''{0}'' failed. The constructor takes ''{1}'' arguments, but there are only ''{2}'' columns in the result set.",
861
          constructor, parameterTypes.length, rsw.getClassNames().size()));
1✔
862
    }
863

864
    for (int i = 0; i < parameterTypes.length; i++) {
1✔
865
      Class<?> parameterType = parameterTypes[i];
1✔
866
      String columnName = rsw.getColumnNames().get(i);
1✔
867
      TypeHandler<?> typeHandler = rsw.getTypeHandler(parameterType, columnName);
1✔
868
      Object value = typeHandler.getResult(rsw.getResultSet(), columnName);
1✔
869
      constructorArgTypes.add(parameterType);
1✔
870
      constructorArgs.add(value);
1✔
871
      foundValues = value != null || foundValues;
1!
872
    }
873
    return foundValues;
1✔
874
  }
875

876
  private boolean applyArgNameBasedConstructorAutoMapping(ResultSetWrapper rsw, ResultMap resultMap,
877
      String columnPrefix, List<Class<?>> constructorArgTypes, List<Object> constructorArgs, Constructor<?> constructor,
878
      boolean foundValues) throws SQLException {
879
    List<String> missingArgs = null;
1✔
880
    Parameter[] params = constructor.getParameters();
1✔
881
    for (Parameter param : params) {
1✔
882
      boolean columnNotFound = true;
1✔
883
      Param paramAnno = param.getAnnotation(Param.class);
1✔
884
      String paramName = paramAnno == null ? param.getName() : paramAnno.value();
1✔
885
      for (String columnName : rsw.getColumnNames()) {
1✔
886
        if (columnMatchesParam(columnName, paramName, columnPrefix)) {
1✔
887
          Class<?> paramType = param.getType();
1✔
888
          TypeHandler<?> typeHandler = rsw.getTypeHandler(paramType, columnName);
1✔
889
          Object value = typeHandler.getResult(rsw.getResultSet(), columnName);
1✔
890
          constructorArgTypes.add(paramType);
1✔
891
          constructorArgs.add(value);
1✔
892
          final String mapKey = resultMap.getId() + ":" + columnPrefix;
1✔
893
          if (!autoMappingsCache.containsKey(mapKey)) {
1!
894
            constructorAutoMappingColumns.computeIfAbsent(mapKey, k -> new ArrayList<>()).add(columnName);
1✔
895
          }
896
          columnNotFound = false;
1✔
897
          foundValues = value != null || foundValues;
1!
898
        }
899
      }
1✔
900
      if (columnNotFound) {
1✔
901
        if (missingArgs == null) {
1!
902
          missingArgs = new ArrayList<>();
1✔
903
        }
904
        missingArgs.add(paramName);
1✔
905
      }
906
    }
907
    if (foundValues && constructorArgs.size() < params.length) {
1✔
908
      throw new ExecutorException(MessageFormat.format(
1✔
909
          "Constructor auto-mapping of ''{1}'' failed " + "because ''{0}'' were not found in the result set; "
910
              + "Available columns are ''{2}'' and mapUnderscoreToCamelCase is ''{3}''.",
911
          missingArgs, constructor, rsw.getColumnNames(), configuration.isMapUnderscoreToCamelCase()));
1✔
912
    }
913
    return foundValues;
1✔
914
  }
915

916
  private boolean columnMatchesParam(String columnName, String paramName, String columnPrefix) {
917
    if (columnPrefix != null) {
1✔
918
      if (!columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
1✔
919
        return false;
1✔
920
      }
921
      columnName = columnName.substring(columnPrefix.length());
1✔
922
    }
923
    return paramName
1✔
924
        .equalsIgnoreCase(configuration.isMapUnderscoreToCamelCase() ? columnName.replace("_", "") : columnName);
1✔
925
  }
926

927
  private Object createPrimitiveResultObject(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix)
928
      throws SQLException {
929
    final Class<?> resultType = resultMap.getType();
1✔
930
    final String columnName;
931
    if (!resultMap.getResultMappings().isEmpty()) {
1✔
932
      final List<ResultMapping> resultMappingList = resultMap.getResultMappings();
1✔
933
      final ResultMapping mapping = resultMappingList.get(0);
1✔
934
      columnName = prependPrefix(mapping.getColumn(), columnPrefix);
1✔
935
    } else {
1✔
936
      columnName = rsw.getColumnNames().get(0);
1✔
937
    }
938
    final TypeHandler<?> typeHandler = rsw.getTypeHandler(resultType, columnName);
1✔
939
    return typeHandler.getResult(rsw.getResultSet(), columnName);
1✔
940
  }
941

942
  //
943
  // NESTED QUERY
944
  //
945

946
  private Object getNestedQueryConstructorValue(ResultSet rs, ResultMapping constructorMapping, String columnPrefix)
947
      throws SQLException {
948
    final String nestedQueryId = constructorMapping.getNestedQueryId();
1✔
949
    final MappedStatement nestedQuery = configuration.getMappedStatement(nestedQueryId);
1✔
950
    final Class<?> nestedQueryParameterType = nestedQuery.getParameterMap().getType();
1✔
951
    final Object nestedQueryParameterObject = prepareParameterForNestedQuery(rs, constructorMapping,
1✔
952
        nestedQueryParameterType, columnPrefix);
953
    Object value = null;
1✔
954
    if (nestedQueryParameterObject != null) {
1!
955
      final BoundSql nestedBoundSql = nestedQuery.getBoundSql(nestedQueryParameterObject);
1✔
956
      final CacheKey key = executor.createCacheKey(nestedQuery, nestedQueryParameterObject, RowBounds.DEFAULT,
1✔
957
          nestedBoundSql);
958
      final Class<?> targetType = constructorMapping.getJavaType();
1✔
959
      final ResultLoader resultLoader = new ResultLoader(configuration, executor, nestedQuery,
1✔
960
          nestedQueryParameterObject, targetType, key, nestedBoundSql);
961
      value = resultLoader.loadResult();
1✔
962
    }
963
    return value;
1✔
964
  }
965

966
  private Object getNestedQueryMappingValue(ResultSet rs, MetaObject metaResultObject, ResultMapping propertyMapping,
967
      ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException {
968
    final String nestedQueryId = propertyMapping.getNestedQueryId();
1✔
969
    final String property = propertyMapping.getProperty();
1✔
970
    final MappedStatement nestedQuery = configuration.getMappedStatement(nestedQueryId);
1✔
971
    final Class<?> nestedQueryParameterType = nestedQuery.getParameterMap().getType();
1✔
972
    final Object nestedQueryParameterObject = prepareParameterForNestedQuery(rs, propertyMapping,
1✔
973
        nestedQueryParameterType, columnPrefix);
974
    Object value = null;
1✔
975
    if (nestedQueryParameterObject != null) {
1✔
976
      final BoundSql nestedBoundSql = nestedQuery.getBoundSql(nestedQueryParameterObject);
1✔
977
      final CacheKey key = executor.createCacheKey(nestedQuery, nestedQueryParameterObject, RowBounds.DEFAULT,
1✔
978
          nestedBoundSql);
979
      final Class<?> targetType = propertyMapping.getJavaType();
1✔
980
      if (executor.isCached(nestedQuery, key)) {
1✔
981
        executor.deferLoad(nestedQuery, metaResultObject, property, key, targetType);
1✔
982
        value = DEFERRED;
1✔
983
      } else {
984
        final ResultLoader resultLoader = new ResultLoader(configuration, executor, nestedQuery,
1✔
985
            nestedQueryParameterObject, targetType, key, nestedBoundSql);
986
        if (propertyMapping.isLazy()) {
1✔
987
          lazyLoader.addLoader(property, metaResultObject, resultLoader);
1✔
988
          value = DEFERRED;
1✔
989
        } else {
990
          value = resultLoader.loadResult();
1✔
991
        }
992
      }
993
    }
994
    return value;
1✔
995
  }
996

997
  private Object prepareParameterForNestedQuery(ResultSet rs, ResultMapping resultMapping, Class<?> parameterType,
998
      String columnPrefix) throws SQLException {
999
    if (resultMapping.isCompositeResult()) {
1✔
1000
      return prepareCompositeKeyParameter(rs, resultMapping, parameterType, columnPrefix);
1✔
1001
    }
1002
    return prepareSimpleKeyParameter(rs, resultMapping, parameterType, columnPrefix);
1✔
1003
  }
1004

1005
  private Object prepareSimpleKeyParameter(ResultSet rs, ResultMapping resultMapping, Class<?> parameterType,
1006
      String columnPrefix) throws SQLException {
1007
    final TypeHandler<?> typeHandler;
1008
    if (typeHandlerRegistry.hasTypeHandler(parameterType)) {
1✔
1009
      typeHandler = typeHandlerRegistry.getTypeHandler(parameterType);
1✔
1010
    } else {
1011
      typeHandler = typeHandlerRegistry.getUnknownTypeHandler();
1✔
1012
    }
1013
    return typeHandler.getResult(rs, prependPrefix(resultMapping.getColumn(), columnPrefix));
1✔
1014
  }
1015

1016
  private Object prepareCompositeKeyParameter(ResultSet rs, ResultMapping resultMapping, Class<?> parameterType,
1017
      String columnPrefix) throws SQLException {
1018
    final Object parameterObject = instantiateParameterObject(parameterType);
1✔
1019
    final MetaObject metaObject = configuration.newMetaObject(parameterObject);
1✔
1020
    boolean foundValues = false;
1✔
1021
    for (ResultMapping innerResultMapping : resultMapping.getComposites()) {
1✔
1022
      final Class<?> propType = metaObject.getSetterType(innerResultMapping.getProperty());
1✔
1023
      final TypeHandler<?> typeHandler = typeHandlerRegistry.getTypeHandler(propType);
1✔
1024
      final Object propValue = typeHandler.getResult(rs, prependPrefix(innerResultMapping.getColumn(), columnPrefix));
1✔
1025
      // issue #353 & #560 do not execute nested query if key is null
1026
      if (propValue != null) {
1✔
1027
        metaObject.setValue(innerResultMapping.getProperty(), propValue);
1✔
1028
        foundValues = true;
1✔
1029
      }
1030
    }
1✔
1031
    return foundValues ? parameterObject : null;
1✔
1032
  }
1033

1034
  private Object instantiateParameterObject(Class<?> parameterType) {
1035
    if (parameterType == null) {
1✔
1036
      return new HashMap<>();
1✔
1037
    }
1038
    if (ParamMap.class.equals(parameterType)) {
1✔
1039
      return new HashMap<>(); // issue #649
1✔
1040
    } else {
1041
      return objectFactory.create(parameterType);
1✔
1042
    }
1043
  }
1044

1045
  //
1046
  // DISCRIMINATOR
1047
  //
1048

1049
  public ResultMap resolveDiscriminatedResultMap(ResultSet rs, ResultMap resultMap, String columnPrefix)
1050
      throws SQLException {
1051
    Set<String> pastDiscriminators = new HashSet<>();
1✔
1052
    Discriminator discriminator = resultMap.getDiscriminator();
1✔
1053
    while (discriminator != null) {
1✔
1054
      final Object value = getDiscriminatorValue(rs, discriminator, columnPrefix);
1✔
1055
      final String discriminatedMapId = discriminator.getMapIdFor(String.valueOf(value));
1✔
1056
      if (!configuration.hasResultMap(discriminatedMapId)) {
1✔
1057
        break;
1✔
1058
      }
1059
      resultMap = configuration.getResultMap(discriminatedMapId);
1✔
1060
      Discriminator lastDiscriminator = discriminator;
1✔
1061
      discriminator = resultMap.getDiscriminator();
1✔
1062
      if (discriminator == lastDiscriminator || !pastDiscriminators.add(discriminatedMapId)) {
1!
1063
        break;
1✔
1064
      }
1065
    }
1✔
1066
    return resultMap;
1✔
1067
  }
1068

1069
  private Object getDiscriminatorValue(ResultSet rs, Discriminator discriminator, String columnPrefix)
1070
      throws SQLException {
1071
    final ResultMapping resultMapping = discriminator.getResultMapping();
1✔
1072
    final TypeHandler<?> typeHandler = resultMapping.getTypeHandler();
1✔
1073
    return typeHandler.getResult(rs, prependPrefix(resultMapping.getColumn(), columnPrefix));
1✔
1074
  }
1075

1076
  private String prependPrefix(String columnName, String prefix) {
1077
    if (columnName == null || columnName.length() == 0 || prefix == null || prefix.length() == 0) {
1!
1078
      return columnName;
1✔
1079
    }
1080
    return prefix + columnName;
1✔
1081
  }
1082

1083
  //
1084
  // HANDLE NESTED RESULT MAPS
1085
  //
1086

1087
  private void handleRowValuesForNestedResultMap(ResultSetWrapper rsw, ResultMap resultMap,
1088
      ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
1089
    final boolean useCollectionConstructorInjection = resultMap.hasResultMapsUsingConstructorCollection();
1✔
1090
    PendingConstructorCreation lastHandledCreation = null;
1✔
1091
    if (useCollectionConstructorInjection) {
1✔
1092
      verifyPendingCreationPreconditions(parentMapping);
1✔
1093
    }
1094

1095
    final DefaultResultContext<Object> resultContext = new DefaultResultContext<>();
1✔
1096
    ResultSet resultSet = rsw.getResultSet();
1✔
1097
    skipRows(resultSet, rowBounds);
1✔
1098
    Object rowValue = previousRowValue;
1✔
1099

1100
    while (shouldProcessMoreRows(resultContext, rowBounds) && !resultSet.isClosed() && resultSet.next()) {
1!
1101
      final ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(resultSet, resultMap, null);
1✔
1102
      final CacheKey rowKey = createRowKey(discriminatedResultMap, rsw, null);
1✔
1103

1104
      final Object partialObject = nestedResultObjects.get(rowKey);
1✔
1105
      final boolean foundNewUniqueRow = partialObject == null;
1✔
1106

1107
      // issue #577, #542 && #101
1108
      if (useCollectionConstructorInjection) {
1✔
1109
        if (foundNewUniqueRow && lastHandledCreation != null) {
1✔
1110
          createAndStorePendingCreation(resultHandler, resultSet, resultContext, lastHandledCreation);
1✔
1111
          lastHandledCreation = null;
1✔
1112
        }
1113

1114
        rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, null, partialObject);
1✔
1115
        if (rowValue instanceof PendingConstructorCreation) {
1!
1116
          lastHandledCreation = (PendingConstructorCreation) rowValue;
1✔
1117
        }
1118
      } else if (mappedStatement.isResultOrdered()) {
1✔
1119
        if (foundNewUniqueRow && rowValue != null) {
1✔
1120
          nestedResultObjects.clear();
1✔
1121
          storeObject(resultHandler, resultContext, rowValue, parentMapping, resultSet);
1✔
1122
        }
1123
        rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, null, partialObject);
1✔
1124
      } else {
1125
        rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, null, partialObject);
1✔
1126
        if (foundNewUniqueRow) {
1✔
1127
          storeObject(resultHandler, resultContext, rowValue, parentMapping, resultSet);
1✔
1128
        }
1129
      }
1130
    }
1✔
1131

1132
    if (useCollectionConstructorInjection && lastHandledCreation != null) {
1!
1133
      createAndStorePendingCreation(resultHandler, resultSet, resultContext, lastHandledCreation);
1✔
1134
    } else if (rowValue != null && mappedStatement.isResultOrdered()
1✔
1135
        && shouldProcessMoreRows(resultContext, rowBounds)) {
1✔
1136
      storeObject(resultHandler, resultContext, rowValue, parentMapping, resultSet);
1✔
1137
      previousRowValue = null;
1✔
1138
    } else if (rowValue != null) {
1✔
1139
      previousRowValue = rowValue;
1✔
1140
    }
1141
  }
1✔
1142

1143
  //
1144
  // NESTED RESULT MAP (PENDING CONSTRUCTOR CREATIONS)
1145
  //
1146
  private void linkNestedPendingCreations(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix,
1147
      CacheKey parentRowKey, PendingConstructorCreation pendingCreation, List<Object> constructorArgs)
1148
      throws SQLException {
1149
    if (parentRowKey == null) {
1!
1150
      // nothing to link, possibly due to simple (non-nested) result map
UNCOV
1151
      return;
×
1152
    }
1153

1154
    final CacheKey rowKey = createRowKey(resultMap, rsw, columnPrefix);
1✔
1155
    final CacheKey combinedKey = combineKeys(rowKey, parentRowKey);
1✔
1156

1157
    if (combinedKey != CacheKey.NULL_CACHE_KEY) {
1!
1158
      nestedResultObjects.put(combinedKey, pendingCreation);
1✔
1159
    }
1160

1161
    final List<ResultMapping> constructorMappings = resultMap.getConstructorResultMappings();
1✔
1162
    for (int index = 0; index < constructorMappings.size(); index++) {
1✔
1163
      final ResultMapping constructorMapping = constructorMappings.get(index);
1✔
1164
      final String nestedResultMapId = constructorMapping.getNestedResultMapId();
1✔
1165

1166
      if (nestedResultMapId == null) {
1✔
1167
        continue;
1✔
1168
      }
1169

1170
      final Class<?> javaType = constructorMapping.getJavaType();
1✔
1171
      if (javaType == null || !objectFactory.isCollection(javaType)) {
1!
1172
        continue;
1✔
1173
      }
1174

1175
      final String constructorColumnPrefix = getColumnPrefix(columnPrefix, constructorMapping);
1✔
1176
      final ResultMap nestedResultMap = resolveDiscriminatedResultMap(rsw.getResultSet(),
1✔
1177
          configuration.getResultMap(constructorMapping.getNestedResultMapId()), constructorColumnPrefix);
1✔
1178

1179
      final Object actualValue = constructorArgs.get(index);
1✔
1180
      final boolean hasValue = actualValue != null;
1✔
1181
      final boolean isInnerCreation = actualValue instanceof PendingConstructorCreation;
1✔
1182
      final boolean alreadyCreatedCollection = hasValue && objectFactory.isCollection(actualValue.getClass());
1!
1183

1184
      if (!isInnerCreation) {
1✔
1185
        final Collection<Object> value = pendingCreation.initializeCollectionForResultMapping(objectFactory,
1✔
1186
            nestedResultMap, constructorMapping, index);
1✔
1187
        if (!alreadyCreatedCollection) {
1!
1188
          // override values with empty collection
1189
          constructorArgs.set(index, value);
1✔
1190
        }
1191

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

1196
        if (nestedCombinedKey != CacheKey.NULL_CACHE_KEY) {
1✔
1197
          nestedResultObjects.put(nestedCombinedKey, pendingCreation);
1✔
1198
        }
1199

1200
        if (hasValue) {
1✔
1201
          pendingCreation.linkCollectionValue(constructorMapping, actualValue);
1✔
1202
        }
1203
      } else {
1✔
1204
        final PendingConstructorCreation innerCreation = (PendingConstructorCreation) actualValue;
1✔
1205
        final Collection<Object> value = pendingCreation.initializeCollectionForResultMapping(objectFactory,
1✔
1206
            nestedResultMap, constructorMapping, index);
1✔
1207
        // we will fill this collection when building the final object
1208
        constructorArgs.set(index, value);
1✔
1209
        // link the creation for building later
1210
        pendingCreation.linkCreation(constructorMapping, innerCreation);
1✔
1211
      }
1212
    }
1213
  }
1✔
1214

1215
  private boolean applyNestedPendingConstructorCreations(ResultSetWrapper rsw, ResultMap resultMap,
1216
      MetaObject metaObject, String parentPrefix, CacheKey parentRowKey, boolean newObject, boolean foundValues) {
1217
    if (newObject) {
1✔
1218
      // new objects are linked by createResultObject
1219
      return false;
1✔
1220
    }
1221

1222
    for (ResultMapping constructorMapping : resultMap.getConstructorResultMappings()) {
1✔
1223
      final String nestedResultMapId = constructorMapping.getNestedResultMapId();
1✔
1224
      final Class<?> parameterType = constructorMapping.getJavaType();
1✔
1225
      if (nestedResultMapId == null || constructorMapping.getResultSet() != null || parameterType == null
1!
1226
          || !objectFactory.isCollection(parameterType)) {
1✔
1227
        continue;
1✔
1228
      }
1229

1230
      try {
1231
        final String columnPrefix = getColumnPrefix(parentPrefix, constructorMapping);
1✔
1232
        final ResultMap nestedResultMap = getNestedResultMap(rsw.getResultSet(), nestedResultMapId, columnPrefix);
1✔
1233

1234
        final CacheKey rowKey = createRowKey(nestedResultMap, rsw, columnPrefix);
1✔
1235
        final CacheKey combinedKey = combineKeys(rowKey, parentRowKey);
1✔
1236

1237
        // should have inserted already as a nested result object
1238
        Object rowValue = nestedResultObjects.get(combinedKey);
1✔
1239

1240
        PendingConstructorCreation pendingConstructorCreation = null;
1✔
1241
        if (rowValue instanceof PendingConstructorCreation) {
1✔
1242
          pendingConstructorCreation = (PendingConstructorCreation) rowValue;
1✔
1243
        } else if (rowValue != null) {
1✔
1244
          // found a simple object that was already linked/handled
1245
          continue;
1✔
1246
        }
1247

1248
        final boolean newValueForNestedResultMap = pendingConstructorCreation == null;
1✔
1249
        if (newValueForNestedResultMap) {
1✔
1250
          final Object parentObject = metaObject.getOriginalObject();
1✔
1251
          if (!(parentObject instanceof PendingConstructorCreation)) {
1!
1252
            throw new ExecutorException(
×
1253
                "parentObject is not a pending creation, cannot continue linking! MyBatis internal error!");
1254
          }
1255

1256
          pendingConstructorCreation = (PendingConstructorCreation) parentObject;
1✔
1257
        }
1258

1259
        rowValue = getRowValue(rsw, nestedResultMap, combinedKey, columnPrefix,
1✔
1260
            newValueForNestedResultMap ? null : pendingConstructorCreation);
1✔
1261

1262
        if (rowValue == null) {
1✔
1263
          continue;
1✔
1264
        }
1265

1266
        if (rowValue instanceof PendingConstructorCreation) {
1✔
1267
          if (newValueForNestedResultMap) {
1✔
1268
            // we created a brand new pcc. this is a new collection value
1269
            pendingConstructorCreation.linkCreation(constructorMapping, (PendingConstructorCreation) rowValue);
1✔
1270
            foundValues = true;
1✔
1271
          }
1272
        } else {
1273
          pendingConstructorCreation.linkCollectionValue(constructorMapping, rowValue);
1✔
1274
          foundValues = true;
1✔
1275

1276
          if (combinedKey != CacheKey.NULL_CACHE_KEY) {
1✔
1277
            nestedResultObjects.put(combinedKey, pendingConstructorCreation);
1✔
1278
          }
1279
        }
1280
      } catch (SQLException e) {
×
1281
        throw new ExecutorException("Error getting constructor collection nested result map values for '"
×
1282
            + constructorMapping.getProperty() + "'.  Cause: " + e, e);
×
1283
      }
1✔
1284
    }
1✔
1285

1286
    return foundValues;
1✔
1287
  }
1288

1289
  private void createPendingConstructorCreations(Object rowValue) {
1290
    // handle possible pending creations within this object
1291
    // by now, the property mapping has been completely built, we can reconstruct it
1292
    final PendingRelation pendingRelation = pendingPccRelations.remove(rowValue);
1✔
1293
    final MetaObject metaObject = pendingRelation.metaObject;
1✔
1294
    final ResultMapping resultMapping = pendingRelation.propertyMapping;
1✔
1295

1296
    // get the list to be built
1297
    Object collectionProperty = instantiateCollectionPropertyIfAppropriate(resultMapping, metaObject);
1✔
1298
    if (collectionProperty != null) {
1!
1299
      // we expect pending creations now
1300
      final Collection<Object> pendingCreations = (Collection<Object>) collectionProperty;
1✔
1301

1302
      // remove the link to the old collection
1303
      metaObject.setValue(resultMapping.getProperty(), null);
1✔
1304

1305
      // create new collection property
1306
      collectionProperty = instantiateCollectionPropertyIfAppropriate(resultMapping, metaObject);
1✔
1307
      final MetaObject targetMetaObject = configuration.newMetaObject(collectionProperty);
1✔
1308

1309
      // create the pending objects
1310
      for (Object pendingCreation : pendingCreations) {
1✔
1311
        if (pendingCreation instanceof PendingConstructorCreation) {
1!
1312
          final PendingConstructorCreation pendingConstructorCreation = (PendingConstructorCreation) pendingCreation;
1✔
1313
          targetMetaObject.add(pendingConstructorCreation.create(objectFactory));
1✔
1314
        }
1315
      }
1✔
1316
    }
1317
  }
1✔
1318

1319
  private void verifyPendingCreationPreconditions(ResultMapping parentMapping) {
1320
    if (parentMapping != null) {
1!
1321
      throw new ExecutorException(
×
1322
          "Cannot construct objects with collections in constructors using multiple result sets yet!");
1323
    }
1324

1325
    if (!mappedStatement.isResultOrdered()) {
1!
1326
      throw new ExecutorException("Cannot reliably construct result if we are not sure the results are ordered "
×
1327
          + "so that no new previous rows would occur, set resultOrdered on your mapped statement if you have verified this");
1328
    }
1329
  }
1✔
1330

1331
  private void createAndStorePendingCreation(ResultHandler<?> resultHandler, ResultSet resultSet,
1332
      DefaultResultContext<Object> resultContext, PendingConstructorCreation pendingCreation) throws SQLException {
1333
    final Object result = pendingCreation.create(objectFactory);
1✔
1334
    storeObject(resultHandler, resultContext, result, null, resultSet);
1✔
1335
    nestedResultObjects.clear();
1✔
1336
  }
1✔
1337

1338
  //
1339
  // NESTED RESULT MAP (JOIN MAPPING)
1340
  //
1341

1342
  private boolean applyNestedResultMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject,
1343
      String parentPrefix, CacheKey parentRowKey, boolean newObject) {
1344
    boolean foundValues = false;
1✔
1345
    for (ResultMapping resultMapping : resultMap.getPropertyResultMappings()) {
1✔
1346
      final String nestedResultMapId = resultMapping.getNestedResultMapId();
1✔
1347
      if (nestedResultMapId != null && resultMapping.getResultSet() == null) {
1!
1348
        try {
1349
          final String columnPrefix = getColumnPrefix(parentPrefix, resultMapping);
1✔
1350
          final ResultMap nestedResultMap = getNestedResultMap(rsw.getResultSet(), nestedResultMapId, columnPrefix);
1✔
1351
          if (resultMapping.getColumnPrefix() == null) {
1✔
1352
            // try to fill circular reference only when columnPrefix
1353
            // is not specified for the nested result map (issue #215)
1354
            Object ancestorObject = ancestorObjects.get(nestedResultMapId);
1✔
1355
            if (ancestorObject != null) {
1✔
1356
              if (newObject) {
1✔
1357
                linkObjects(metaObject, resultMapping, ancestorObject); // issue #385
1✔
1358
              }
1359
              continue;
1✔
1360
            }
1361
          }
1362
          final CacheKey rowKey = createRowKey(nestedResultMap, rsw, columnPrefix);
1✔
1363
          final CacheKey combinedKey = combineKeys(rowKey, parentRowKey);
1✔
1364
          Object rowValue = nestedResultObjects.get(combinedKey);
1✔
1365
          boolean knownValue = rowValue != null;
1✔
1366
          instantiateCollectionPropertyIfAppropriate(resultMapping, metaObject); // mandatory
1✔
1367
          if (anyNotNullColumnHasValue(resultMapping, columnPrefix, rsw)) {
1✔
1368
            rowValue = getRowValue(rsw, nestedResultMap, combinedKey, columnPrefix, rowValue);
1✔
1369
            if (rowValue != null && !knownValue) {
1✔
1370
              linkObjects(metaObject, resultMapping, rowValue);
1✔
1371
              foundValues = true;
1✔
1372
            }
1373
          }
1374
        } catch (SQLException e) {
×
1375
          throw new ExecutorException(
×
1376
              "Error getting nested result map values for '" + resultMapping.getProperty() + "'.  Cause: " + e, e);
×
1377
        }
1✔
1378
      }
1379
    }
1✔
1380

1381
    // (issue #101)
1382
    if (resultMap.hasResultMapsUsingConstructorCollection()) {
1✔
1383
      foundValues = applyNestedPendingConstructorCreations(rsw, resultMap, metaObject, parentPrefix, parentRowKey,
1✔
1384
          newObject, foundValues);
1385
    }
1386

1387
    return foundValues;
1✔
1388
  }
1389

1390
  private String getColumnPrefix(String parentPrefix, ResultMapping resultMapping) {
1391
    final StringBuilder columnPrefixBuilder = new StringBuilder();
1✔
1392
    if (parentPrefix != null) {
1✔
1393
      columnPrefixBuilder.append(parentPrefix);
1✔
1394
    }
1395
    if (resultMapping.getColumnPrefix() != null) {
1✔
1396
      columnPrefixBuilder.append(resultMapping.getColumnPrefix());
1✔
1397
    }
1398
    return columnPrefixBuilder.length() == 0 ? null : columnPrefixBuilder.toString().toUpperCase(Locale.ENGLISH);
1✔
1399
  }
1400

1401
  private boolean anyNotNullColumnHasValue(ResultMapping resultMapping, String columnPrefix, ResultSetWrapper rsw)
1402
      throws SQLException {
1403
    Set<String> notNullColumns = resultMapping.getNotNullColumns();
1✔
1404
    if (notNullColumns != null && !notNullColumns.isEmpty()) {
1✔
1405
      ResultSet rs = rsw.getResultSet();
1✔
1406
      for (String column : notNullColumns) {
1✔
1407
        rs.getObject(prependPrefix(column, columnPrefix));
1✔
1408
        if (!rs.wasNull()) {
1✔
1409
          return true;
1✔
1410
        }
1411
      }
1✔
1412
      return false;
1✔
1413
    }
1414
    if (columnPrefix != null) {
1✔
1415
      for (String columnName : rsw.getColumnNames()) {
1✔
1416
        if (columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix.toUpperCase(Locale.ENGLISH))) {
1✔
1417
          return true;
1✔
1418
        }
1419
      }
1✔
1420
      return false;
1✔
1421
    }
1422
    return true;
1✔
1423
  }
1424

1425
  private ResultMap getNestedResultMap(ResultSet rs, String nestedResultMapId, String columnPrefix)
1426
      throws SQLException {
1427
    ResultMap nestedResultMap = configuration.getResultMap(nestedResultMapId);
1✔
1428
    return resolveDiscriminatedResultMap(rs, nestedResultMap, columnPrefix);
1✔
1429
  }
1430

1431
  //
1432
  // UNIQUE RESULT KEY
1433
  //
1434

1435
  private CacheKey createRowKey(ResultMap resultMap, ResultSetWrapper rsw, String columnPrefix) throws SQLException {
1436
    final CacheKey cacheKey = new CacheKey();
1✔
1437
    cacheKey.update(resultMap.getId());
1✔
1438
    List<ResultMapping> resultMappings = getResultMappingsForRowKey(resultMap);
1✔
1439
    if (resultMappings.isEmpty()) {
1✔
1440
      if (Map.class.isAssignableFrom(resultMap.getType())) {
1!
1441
        createRowKeyForMap(rsw, cacheKey);
×
1442
      } else {
1443
        createRowKeyForUnmappedProperties(resultMap, rsw, cacheKey, columnPrefix);
1✔
1444
      }
1445
    } else {
1446
      createRowKeyForMappedProperties(resultMap, rsw, cacheKey, resultMappings, columnPrefix);
1✔
1447
    }
1448
    if (cacheKey.getUpdateCount() < 2) {
1✔
1449
      return CacheKey.NULL_CACHE_KEY;
1✔
1450
    }
1451
    return cacheKey;
1✔
1452
  }
1453

1454
  private CacheKey combineKeys(CacheKey rowKey, CacheKey parentRowKey) {
1455
    if (rowKey.getUpdateCount() > 1 && parentRowKey.getUpdateCount() > 1) {
1✔
1456
      CacheKey combinedKey;
1457
      try {
1458
        combinedKey = rowKey.clone();
1✔
1459
      } catch (CloneNotSupportedException e) {
×
1460
        throw new ExecutorException("Error cloning cache key.  Cause: " + e, e);
×
1461
      }
1✔
1462
      combinedKey.update(parentRowKey);
1✔
1463
      return combinedKey;
1✔
1464
    }
1465
    return CacheKey.NULL_CACHE_KEY;
1✔
1466
  }
1467

1468
  private List<ResultMapping> getResultMappingsForRowKey(ResultMap resultMap) {
1469
    List<ResultMapping> resultMappings = resultMap.getIdResultMappings();
1✔
1470
    if (resultMappings.isEmpty()) {
1✔
1471
      resultMappings = resultMap.getPropertyResultMappings();
1✔
1472
    }
1473
    return resultMappings;
1✔
1474
  }
1475

1476
  private void createRowKeyForMappedProperties(ResultMap resultMap, ResultSetWrapper rsw, CacheKey cacheKey,
1477
      List<ResultMapping> resultMappings, String columnPrefix) throws SQLException {
1478
    for (ResultMapping resultMapping : resultMappings) {
1✔
1479
      if (resultMapping.isSimple()) {
1✔
1480
        final String column = prependPrefix(resultMapping.getColumn(), columnPrefix);
1✔
1481
        final TypeHandler<?> th = resultMapping.getTypeHandler();
1✔
1482
        Set<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix);
1✔
1483
        // Issue #114
1484
        if (column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH))) {
1!
1485
          final Object value = th.getResult(rsw.getResultSet(), column);
1✔
1486
          if (value != null || configuration.isReturnInstanceForEmptyRow()) {
1✔
1487
            cacheKey.update(column);
1✔
1488
            cacheKey.update(value);
1✔
1489
          }
1490
        }
1491
      }
1492
    }
1✔
1493
  }
1✔
1494

1495
  private void createRowKeyForUnmappedProperties(ResultMap resultMap, ResultSetWrapper rsw, CacheKey cacheKey,
1496
      String columnPrefix) throws SQLException {
1497
    final MetaClass metaType = MetaClass.forClass(resultMap.getType(), reflectorFactory);
1✔
1498
    List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
1✔
1499
    for (String column : unmappedColumnNames) {
1✔
1500
      String property = column;
1✔
1501
      if (columnPrefix != null && !columnPrefix.isEmpty()) {
1!
1502
        // When columnPrefix is specified, ignore columns without the prefix.
1503
        if (!column.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
1✔
1504
          continue;
1✔
1505
        }
1506
        property = column.substring(columnPrefix.length());
1✔
1507
      }
1508
      if (metaType.findProperty(property, configuration.isMapUnderscoreToCamelCase()) != null) {
1✔
1509
        String value = rsw.getResultSet().getString(column);
1✔
1510
        if (value != null) {
1✔
1511
          cacheKey.update(column);
1✔
1512
          cacheKey.update(value);
1✔
1513
        }
1514
      }
1515
    }
1✔
1516
  }
1✔
1517

1518
  private void createRowKeyForMap(ResultSetWrapper rsw, CacheKey cacheKey) throws SQLException {
1519
    List<String> columnNames = rsw.getColumnNames();
×
1520
    for (String columnName : columnNames) {
×
1521
      final String value = rsw.getResultSet().getString(columnName);
×
1522
      if (value != null) {
×
1523
        cacheKey.update(columnName);
×
1524
        cacheKey.update(value);
×
1525
      }
1526
    }
×
1527
  }
×
1528

1529
  private void linkObjects(MetaObject metaObject, ResultMapping resultMapping, Object rowValue) {
1530
    final Object collectionProperty = instantiateCollectionPropertyIfAppropriate(resultMapping, metaObject);
1✔
1531
    if (collectionProperty != null) {
1✔
1532
      final MetaObject targetMetaObject = configuration.newMetaObject(collectionProperty);
1✔
1533
      targetMetaObject.add(rowValue);
1✔
1534

1535
      // it is possible for pending creations to get set via property mappings,
1536
      // keep track of these, so we can rebuild them.
1537
      final Object originalObject = metaObject.getOriginalObject();
1✔
1538
      if (rowValue instanceof PendingConstructorCreation && !pendingPccRelations.containsKey(originalObject)) {
1✔
1539
        PendingRelation pendingRelation = new PendingRelation();
1✔
1540
        pendingRelation.propertyMapping = resultMapping;
1✔
1541
        pendingRelation.metaObject = metaObject;
1✔
1542

1543
        pendingPccRelations.put(originalObject, pendingRelation);
1✔
1544
      }
1545
    } else {
1✔
1546
      metaObject.setValue(resultMapping.getProperty(), rowValue);
1✔
1547
    }
1548
  }
1✔
1549

1550
  private Object instantiateCollectionPropertyIfAppropriate(ResultMapping resultMapping, MetaObject metaObject) {
1551
    final String propertyName = resultMapping.getProperty();
1✔
1552
    Object propertyValue = metaObject.getValue(propertyName);
1✔
1553
    if (propertyValue == null) {
1✔
1554
      Class<?> type = resultMapping.getJavaType();
1✔
1555
      if (type == null) {
1✔
1556
        type = metaObject.getSetterType(propertyName);
1✔
1557
      }
1558
      try {
1559
        if (objectFactory.isCollection(type)) {
1✔
1560
          propertyValue = objectFactory.create(type);
1✔
1561
          metaObject.setValue(propertyName, propertyValue);
1✔
1562
          return propertyValue;
1✔
1563
        }
1564
      } catch (Exception e) {
×
1565
        throw new ExecutorException(
×
1566
            "Error instantiating collection property for result '" + resultMapping.getProperty() + "'.  Cause: " + e,
×
1567
            e);
1568
      }
1✔
1569
    } else if (objectFactory.isCollection(propertyValue.getClass())) {
1✔
1570
      return propertyValue;
1✔
1571
    }
1572
    return null;
1✔
1573
  }
1574

1575
  private boolean hasTypeHandlerForResultObject(ResultSetWrapper rsw, Class<?> resultType) {
1576
    if (rsw.getColumnNames().size() == 1) {
1✔
1577
      return typeHandlerRegistry.hasTypeHandler(resultType, rsw.getJdbcType(rsw.getColumnNames().get(0)));
1✔
1578
    }
1579
    return typeHandlerRegistry.hasTypeHandler(resultType);
1✔
1580
  }
1581

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

© 2026 Coveralls, Inc