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

mybatis / mybatis-3 / 2604

03 Jan 2025 10:00AM UTC coverage: 87.524% (+0.3%) from 87.177%
2604

Pull #3146

github

web-flow
Merge 60c1f5fea into 8ac3920af
Pull Request #3146: Shared ambiguity instance

3633 of 4401 branches covered (82.55%)

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

254 existing lines in 22 files now uncovered.

9569 of 10933 relevant lines covered (87.52%)

0.88 hits per line

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

96.0
/src/main/java/org/apache/ibatis/builder/xml/XMLMapperBuilder.java
1
/*
2
 *    Copyright 2009-2024 the original author or authors.
3
 *
4
 *    Licensed under the Apache License, Version 2.0 (the "License");
5
 *    you may not use this file except in compliance with the License.
6
 *    You may obtain a copy of the License at
7
 *
8
 *       https://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *    Unless required by applicable law or agreed to in writing, software
11
 *    distributed under the License is distributed on an "AS IS" BASIS,
12
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *    See the License for the specific language governing permissions and
14
 *    limitations under the License.
15
 */
16
package org.apache.ibatis.builder.xml;
17

18
import java.io.InputStream;
19
import java.io.Reader;
20
import java.util.ArrayList;
21
import java.util.Arrays;
22
import java.util.Collections;
23
import java.util.HashMap;
24
import java.util.List;
25
import java.util.Map;
26
import java.util.Properties;
27

28
import org.apache.ibatis.builder.BaseBuilder;
29
import org.apache.ibatis.builder.BuilderException;
30
import org.apache.ibatis.builder.CacheRefResolver;
31
import org.apache.ibatis.builder.IncompleteElementException;
32
import org.apache.ibatis.builder.MapperBuilderAssistant;
33
import org.apache.ibatis.builder.ResultMapResolver;
34
import org.apache.ibatis.cache.Cache;
35
import org.apache.ibatis.executor.ErrorContext;
36
import org.apache.ibatis.io.Resources;
37
import org.apache.ibatis.mapping.Discriminator;
38
import org.apache.ibatis.mapping.ParameterMapping;
39
import org.apache.ibatis.mapping.ParameterMode;
40
import org.apache.ibatis.mapping.ResultFlag;
41
import org.apache.ibatis.mapping.ResultMap;
42
import org.apache.ibatis.mapping.ResultMapping;
43
import org.apache.ibatis.parsing.XNode;
44
import org.apache.ibatis.parsing.XPathParser;
45
import org.apache.ibatis.reflection.MetaClass;
46
import org.apache.ibatis.session.Configuration;
47
import org.apache.ibatis.type.JdbcType;
48
import org.apache.ibatis.type.TypeHandler;
49

50
/**
51
 * @author Clinton Begin
52
 * @author Kazuki Shimizu
53
 */
54
public class XMLMapperBuilder extends BaseBuilder {
55

56
  private final XPathParser parser;
57
  private final MapperBuilderAssistant builderAssistant;
58
  private final Map<String, XNode> sqlFragments;
59
  private final String resource;
60

61
  @Deprecated
62
  public XMLMapperBuilder(Reader reader, Configuration configuration, String resource, Map<String, XNode> sqlFragments,
63
      String namespace) {
64
    this(reader, configuration, resource, sqlFragments);
×
65
    this.builderAssistant.setCurrentNamespace(namespace);
×
66
  }
×
67

68
  @Deprecated
69
  public XMLMapperBuilder(Reader reader, Configuration configuration, String resource,
70
      Map<String, XNode> sqlFragments) {
71
    this(new XPathParser(reader, true, configuration.getVariables(), new XMLMapperEntityResolver()), configuration,
×
72
        resource, sqlFragments);
73
  }
×
74

75
  public XMLMapperBuilder(InputStream inputStream, Configuration configuration, String resource,
76
      Map<String, XNode> sqlFragments, String namespace) {
77
    this(inputStream, configuration, resource, sqlFragments);
1✔
78
    this.builderAssistant.setCurrentNamespace(namespace);
1✔
79
  }
1✔
80

81
  public XMLMapperBuilder(InputStream inputStream, Configuration configuration, String resource,
82
      Map<String, XNode> sqlFragments) {
83
    this(new XPathParser(inputStream, true, configuration.getVariables(), new XMLMapperEntityResolver()), configuration,
1✔
84
        resource, sqlFragments);
85
  }
1✔
86

87
  private XMLMapperBuilder(XPathParser parser, Configuration configuration, String resource,
88
      Map<String, XNode> sqlFragments) {
89
    super(configuration);
1✔
90
    this.builderAssistant = new MapperBuilderAssistant(configuration, resource);
1✔
91
    this.parser = parser;
1✔
92
    this.sqlFragments = sqlFragments;
1✔
93
    this.resource = resource;
1✔
94
  }
1✔
95

96
  public void parse() {
97
    if (!configuration.isResourceLoaded(resource)) {
1!
98
      configurationElement(parser.evalNode("/mapper"));
1✔
99
      configuration.addLoadedResource(resource);
1✔
100
      bindMapperForNamespace();
1✔
101
    }
102
    configuration.parsePendingResultMaps(false);
1✔
103
    configuration.parsePendingCacheRefs(false);
1✔
104
    configuration.parsePendingStatements(false);
1✔
105
  }
1✔
106

107
  public XNode getSqlFragment(String refid) {
108
    return sqlFragments.get(refid);
×
109
  }
110

111
  private void configurationElement(XNode context) {
112
    try {
113
      String namespace = context.getStringAttribute("namespace");
1✔
114
      if (namespace == null || namespace.isEmpty()) {
1✔
115
        throw new BuilderException("Mapper's namespace cannot be empty");
1✔
116
      }
117
      builderAssistant.setCurrentNamespace(namespace);
1✔
118
      cacheRefElement(context.evalNode("cache-ref"));
1✔
119
      cacheElement(context.evalNode("cache"));
1✔
120
      parameterMapElement(context.evalNodes("/mapper/parameterMap"));
1✔
121
      resultMapElements(context.evalNodes("/mapper/resultMap"));
1✔
122
      sqlElement(context.evalNodes("/mapper/sql"));
1✔
123
      buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
1✔
124
    } catch (Exception e) {
1✔
125
      throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
1✔
126
    }
1✔
127
  }
1✔
128

129
  private void buildStatementFromContext(List<XNode> list) {
130
    if (configuration.getDatabaseId() != null) {
1✔
131
      buildStatementFromContext(list, configuration.getDatabaseId());
1✔
132
    }
133
    buildStatementFromContext(list, null);
1✔
134
  }
1✔
135

136
  private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
137
    for (XNode context : list) {
1✔
138
      final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context,
1✔
139
          requiredDatabaseId);
140
      try {
141
        statementParser.parseStatementNode();
1✔
142
      } catch (IncompleteElementException e) {
1✔
143
        configuration.addIncompleteStatement(statementParser);
1✔
144
      }
1✔
145
    }
1✔
146
  }
1✔
147

148
  private void cacheRefElement(XNode context) {
149
    if (context != null) {
1✔
150
      configuration.addCacheRef(builderAssistant.getCurrentNamespace(), context.getStringAttribute("namespace"));
1✔
151
      CacheRefResolver cacheRefResolver = new CacheRefResolver(builderAssistant,
1✔
152
          context.getStringAttribute("namespace"));
1✔
153
      try {
154
        cacheRefResolver.resolveCacheRef();
×
155
      } catch (IncompleteElementException e) {
1✔
156
        configuration.addIncompleteCacheRef(cacheRefResolver);
1✔
157
      }
×
158
    }
159
  }
1✔
160

161
  private void cacheElement(XNode context) {
162
    if (context != null) {
1✔
163
      String type = context.getStringAttribute("type", "PERPETUAL");
1✔
164
      Class<? extends Cache> typeClass = typeAliasRegistry.resolveAlias(type);
1✔
165
      String eviction = context.getStringAttribute("eviction", "LRU");
1✔
166
      Class<? extends Cache> evictionClass = typeAliasRegistry.resolveAlias(eviction);
1✔
167
      Long flushInterval = context.getLongAttribute("flushInterval");
1✔
168
      Integer size = context.getIntAttribute("size");
1✔
169
      boolean readWrite = !context.getBooleanAttribute("readOnly", false);
1✔
170
      boolean blocking = context.getBooleanAttribute("blocking", false);
1✔
171
      Properties props = context.getChildrenAsProperties();
1✔
172
      builderAssistant.useNewCache(typeClass, evictionClass, flushInterval, size, readWrite, blocking, props);
1✔
173
    }
174
  }
1✔
175

176
  private void parameterMapElement(List<XNode> list) {
177
    for (XNode parameterMapNode : list) {
1✔
178
      String id = parameterMapNode.getStringAttribute("id");
1✔
179
      String type = parameterMapNode.getStringAttribute("type");
1✔
180
      Class<?> parameterClass = resolveClass(type);
1✔
181
      List<XNode> parameterNodes = parameterMapNode.evalNodes("parameter");
1✔
182
      List<ParameterMapping> parameterMappings = new ArrayList<>();
1✔
183
      for (XNode parameterNode : parameterNodes) {
1✔
184
        String property = parameterNode.getStringAttribute("property");
1✔
185
        String javaType = parameterNode.getStringAttribute("javaType");
1✔
186
        String jdbcType = parameterNode.getStringAttribute("jdbcType");
1✔
187
        String resultMap = parameterNode.getStringAttribute("resultMap");
1✔
188
        String mode = parameterNode.getStringAttribute("mode");
1✔
189
        String typeHandler = parameterNode.getStringAttribute("typeHandler");
1✔
190
        Integer numericScale = parameterNode.getIntAttribute("numericScale");
1✔
191
        ParameterMode modeEnum = resolveParameterMode(mode);
1✔
192
        Class<?> javaTypeClass = resolveClass(javaType);
1✔
193
        JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
1✔
194
        Class<? extends TypeHandler<?>> typeHandlerClass = resolveClass(typeHandler);
1✔
195
        ParameterMapping parameterMapping = builderAssistant.buildParameterMapping(parameterClass, property,
1✔
196
            javaTypeClass, jdbcTypeEnum, resultMap, modeEnum, typeHandlerClass, numericScale);
197
        parameterMappings.add(parameterMapping);
1✔
198
      }
1✔
199
      builderAssistant.addParameterMap(id, parameterClass, parameterMappings);
1✔
200
    }
1✔
201
  }
1✔
202

203
  private void resultMapElements(List<XNode> list) {
204
    for (XNode resultMapNode : list) {
1✔
205
      try {
206
        resultMapElement(resultMapNode);
1✔
207
      } catch (IncompleteElementException e) {
1✔
208
        // ignore, it will be retried
209
      }
1✔
210
    }
1✔
211
  }
1✔
212

213
  private ResultMap resultMapElement(XNode resultMapNode) {
214
    return resultMapElement(resultMapNode, Collections.emptyList(), null);
1✔
215
  }
216

217
  private ResultMap resultMapElement(XNode resultMapNode, List<ResultMapping> additionalResultMappings,
218
      Class<?> enclosingType) {
219
    ErrorContext.instance().activity("processing " + resultMapNode.getValueBasedIdentifier());
1✔
220
    String type = resultMapNode.getStringAttribute("type", resultMapNode.getStringAttribute("ofType",
1✔
221
        resultMapNode.getStringAttribute("resultType", resultMapNode.getStringAttribute("javaType"))));
1✔
222
    Class<?> typeClass = resolveClass(type);
1✔
223
    if (typeClass == null) {
1✔
224
      typeClass = inheritEnclosingType(resultMapNode, enclosingType);
1✔
225
    }
226
    Discriminator discriminator = null;
1✔
227
    List<ResultMapping> resultMappings = new ArrayList<>(additionalResultMappings);
1✔
228
    List<XNode> resultChildren = resultMapNode.getChildren();
1✔
229
    for (XNode resultChild : resultChildren) {
1✔
230
      if ("constructor".equals(resultChild.getName())) {
1✔
231
        processConstructorElement(resultChild, typeClass, resultMappings);
1✔
232
      } else if ("discriminator".equals(resultChild.getName())) {
1✔
233
        discriminator = processDiscriminatorElement(resultChild, typeClass, resultMappings);
1✔
234
      } else {
235
        List<ResultFlag> flags = new ArrayList<>();
1✔
236
        if ("id".equals(resultChild.getName())) {
1✔
237
          flags.add(ResultFlag.ID);
1✔
238
        }
239
        resultMappings.add(buildResultMappingFromContext(resultChild, typeClass, flags));
1✔
240
      }
241
    }
1✔
242
    String id = resultMapNode.getStringAttribute("id", resultMapNode::getValueBasedIdentifier);
1✔
243
    String extend = resultMapNode.getStringAttribute("extends");
1✔
244
    Boolean autoMapping = resultMapNode.getBooleanAttribute("autoMapping");
1✔
245
    ResultMapResolver resultMapResolver = new ResultMapResolver(builderAssistant, id, typeClass, extend, discriminator,
1✔
246
        resultMappings, autoMapping);
247
    try {
248
      return resultMapResolver.resolve();
1✔
249
    } catch (IncompleteElementException e) {
1✔
250
      configuration.addIncompleteResultMap(resultMapResolver);
1✔
251
      throw e;
1✔
252
    }
253
  }
254

255
  protected Class<?> inheritEnclosingType(XNode resultMapNode, Class<?> enclosingType) {
256
    if ("association".equals(resultMapNode.getName()) && resultMapNode.getStringAttribute("resultMap") == null) {
1!
257
      String property = resultMapNode.getStringAttribute("property");
1✔
258
      if (property != null && enclosingType != null) {
1!
259
        MetaClass metaResultType = MetaClass.forClass(enclosingType, configuration.getReflectorFactory());
1✔
260
        return metaResultType.getSetterType(property);
1✔
261
      }
262
    } else if ("case".equals(resultMapNode.getName()) && resultMapNode.getStringAttribute("resultMap") == null) {
1!
263
      return enclosingType;
1✔
264
    }
UNCOV
265
    return null;
×
266
  }
267

268
  private void processConstructorElement(XNode resultChild, Class<?> resultType, List<ResultMapping> resultMappings) {
269
    List<XNode> argChildren = resultChild.getChildren();
1✔
270
    for (XNode argChild : argChildren) {
1✔
271
      List<ResultFlag> flags = new ArrayList<>();
1✔
272
      flags.add(ResultFlag.CONSTRUCTOR);
1✔
273
      if ("idArg".equals(argChild.getName())) {
1✔
274
        flags.add(ResultFlag.ID);
1✔
275
      }
276
      resultMappings.add(buildResultMappingFromContext(argChild, resultType, flags));
1✔
277
    }
1✔
278
  }
1✔
279

280
  private Discriminator processDiscriminatorElement(XNode context, Class<?> resultType,
281
      List<ResultMapping> resultMappings) {
282
    String column = context.getStringAttribute("column");
1✔
283
    String javaType = context.getStringAttribute("javaType");
1✔
284
    String jdbcType = context.getStringAttribute("jdbcType");
1✔
285
    String typeHandler = context.getStringAttribute("typeHandler");
1✔
286
    Class<?> javaTypeClass = resolveClass(javaType);
1✔
287
    Class<? extends TypeHandler<?>> typeHandlerClass = resolveClass(typeHandler);
1✔
288
    JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
1✔
289
    Map<String, String> discriminatorMap = new HashMap<>();
1✔
290
    for (XNode caseChild : context.getChildren()) {
1✔
291
      String value = caseChild.getStringAttribute("value");
1✔
292
      String resultMap = caseChild.getStringAttribute("resultMap",
1✔
293
          () -> processNestedResultMappings(caseChild, resultMappings, resultType));
1✔
294
      discriminatorMap.put(value, resultMap);
1✔
295
    }
1✔
296
    return builderAssistant.buildDiscriminator(resultType, column, javaTypeClass, jdbcTypeEnum, typeHandlerClass,
1✔
297
        discriminatorMap);
298
  }
299

300
  private void sqlElement(List<XNode> list) {
301
    if (configuration.getDatabaseId() != null) {
1✔
302
      sqlElement(list, configuration.getDatabaseId());
1✔
303
    }
304
    sqlElement(list, null);
1✔
305
  }
1✔
306

307
  private void sqlElement(List<XNode> list, String requiredDatabaseId) {
308
    for (XNode context : list) {
1✔
309
      String databaseId = context.getStringAttribute("databaseId");
1✔
310
      String id = context.getStringAttribute("id");
1✔
311
      id = builderAssistant.applyCurrentNamespace(id, false);
1✔
312
      if (databaseIdMatchesCurrent(id, databaseId, requiredDatabaseId)) {
1✔
313
        sqlFragments.put(id, context);
1✔
314
      }
315
    }
1✔
316
  }
1✔
317

318
  private boolean databaseIdMatchesCurrent(String id, String databaseId, String requiredDatabaseId) {
319
    if (requiredDatabaseId != null) {
1✔
320
      return requiredDatabaseId.equals(databaseId);
1✔
321
    }
322
    if (databaseId != null) {
1✔
323
      return false;
1✔
324
    }
325
    if (!this.sqlFragments.containsKey(id)) {
1✔
326
      return true;
1✔
327
    }
328
    // skip this fragment if there is a previous one with a not null databaseId
329
    XNode context = this.sqlFragments.get(id);
1✔
330
    return context.getStringAttribute("databaseId") == null;
1!
331
  }
332

333
  private ResultMapping buildResultMappingFromContext(XNode context, Class<?> resultType, List<ResultFlag> flags) {
334
    String property;
335
    if (flags.contains(ResultFlag.CONSTRUCTOR)) {
1✔
336
      property = context.getStringAttribute("name");
1✔
337
    } else {
338
      property = context.getStringAttribute("property");
1✔
339
    }
340
    String column = context.getStringAttribute("column");
1✔
341
    String javaType = context.getStringAttribute("javaType");
1✔
342
    String jdbcType = context.getStringAttribute("jdbcType");
1✔
343
    String nestedSelect = context.getStringAttribute("select");
1✔
344
    String nestedResultMap = context.getStringAttribute("resultMap",
1✔
345
        () -> processNestedResultMappings(context, Collections.emptyList(), resultType));
1✔
346
    String notNullColumn = context.getStringAttribute("notNullColumn");
1✔
347
    String columnPrefix = context.getStringAttribute("columnPrefix");
1✔
348
    String typeHandler = context.getStringAttribute("typeHandler");
1✔
349
    String resultSet = context.getStringAttribute("resultSet");
1✔
350
    String foreignColumn = context.getStringAttribute("foreignColumn");
1✔
351
    boolean lazy = "lazy"
1✔
352
        .equals(context.getStringAttribute("fetchType", configuration.isLazyLoadingEnabled() ? "lazy" : "eager"));
1✔
353
    Class<?> javaTypeClass = resolveClass(javaType);
1✔
354
    Class<? extends TypeHandler<?>> typeHandlerClass = resolveClass(typeHandler);
1✔
355
    JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
1✔
356
    return builderAssistant.buildResultMapping(resultType, property, column, javaTypeClass, jdbcTypeEnum, nestedSelect,
1✔
357
        nestedResultMap, notNullColumn, columnPrefix, typeHandlerClass, flags, resultSet, foreignColumn, lazy);
358
  }
359

360
  private String processNestedResultMappings(XNode context, List<ResultMapping> resultMappings,
361
      Class<?> enclosingType) {
362
    if (Arrays.asList("association", "collection", "case").contains(context.getName())
1✔
363
        && context.getStringAttribute("select") == null) {
1✔
364
      validateCollection(context, enclosingType);
1✔
365
      ResultMap resultMap = resultMapElement(context, resultMappings, enclosingType);
1✔
366
      return resultMap.getId();
1✔
367
    }
368
    return null;
1✔
369
  }
370

371
  protected void validateCollection(XNode context, Class<?> enclosingType) {
372
    if ("collection".equals(context.getName()) && context.getStringAttribute("resultMap") == null
1!
373
        && context.getStringAttribute("javaType") == null) {
1✔
374
      MetaClass metaResultType = MetaClass.forClass(enclosingType, configuration.getReflectorFactory());
1✔
375
      String property = context.getStringAttribute("property");
1✔
376
      if (!metaResultType.hasSetter(property)) {
1✔
377
        throw new BuilderException(
1✔
378
            "Ambiguous collection type for property '" + property + "'. You must specify 'javaType' or 'resultMap'.");
379
      }
380
    }
381
  }
1✔
382

383
  private void bindMapperForNamespace() {
384
    String namespace = builderAssistant.getCurrentNamespace();
1✔
385
    if (namespace != null) {
1!
386
      Class<?> boundType = null;
1✔
387
      try {
388
        boundType = Resources.classForName(namespace);
1✔
389
      } catch (ClassNotFoundException e) {
1✔
390
        // ignore, bound type is not required
391
      }
1✔
392
      if (boundType != null && !configuration.hasMapper(boundType)) {
1✔
393
        // Spring may not know the real resource name so we set a flag
394
        // to prevent loading again this resource from the mapper interface
395
        // look at MapperAnnotationBuilder#loadXmlResource
396
        configuration.addLoadedResource("namespace:" + namespace);
1✔
397
        configuration.addMapper(boundType);
1✔
398
      }
399
    }
400
  }
1✔
401

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