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

mybatis / mybatis-3 / #3393

25 Dec 2023 01:42AM UTC coverage: 86.665% (+0.05%) from 86.619%
#3393

Pull #2971

github

web-flow
Merge 9b99f44b6 into 01225f508
Pull Request #2971: docs: add dynamic sql example to @Select

3498 of 4275 branches covered (0.0%)

9294 of 10724 relevant lines covered (86.67%)

0.87 hits per line

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

90.23
/src/main/java/org/apache/ibatis/builder/xml/XMLConfigBuilder.java
1
/*
2
 *    Copyright 2009-2023 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.Properties;
21

22
import javax.sql.DataSource;
23

24
import org.apache.ibatis.builder.BaseBuilder;
25
import org.apache.ibatis.builder.BuilderException;
26
import org.apache.ibatis.datasource.DataSourceFactory;
27
import org.apache.ibatis.executor.ErrorContext;
28
import org.apache.ibatis.executor.loader.ProxyFactory;
29
import org.apache.ibatis.io.Resources;
30
import org.apache.ibatis.io.VFS;
31
import org.apache.ibatis.logging.Log;
32
import org.apache.ibatis.mapping.DatabaseIdProvider;
33
import org.apache.ibatis.mapping.Environment;
34
import org.apache.ibatis.parsing.XNode;
35
import org.apache.ibatis.parsing.XPathParser;
36
import org.apache.ibatis.plugin.Interceptor;
37
import org.apache.ibatis.reflection.DefaultReflectorFactory;
38
import org.apache.ibatis.reflection.MetaClass;
39
import org.apache.ibatis.reflection.ReflectorFactory;
40
import org.apache.ibatis.reflection.factory.ObjectFactory;
41
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
42
import org.apache.ibatis.session.AutoMappingBehavior;
43
import org.apache.ibatis.session.AutoMappingUnknownColumnBehavior;
44
import org.apache.ibatis.session.Configuration;
45
import org.apache.ibatis.session.ExecutorType;
46
import org.apache.ibatis.session.LocalCacheScope;
47
import org.apache.ibatis.transaction.TransactionFactory;
48
import org.apache.ibatis.type.JdbcType;
49

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

56
  private boolean parsed;
57
  private final XPathParser parser;
58
  private String environment;
59
  private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();
1✔
60

61
  public XMLConfigBuilder(Reader reader) {
62
    this(reader, null, null);
1✔
63
  }
1✔
64

65
  public XMLConfigBuilder(Reader reader, String environment) {
66
    this(reader, environment, null);
×
67
  }
×
68

69
  public XMLConfigBuilder(Reader reader, String environment, Properties props) {
70
    this(Configuration.class, reader, environment, props);
1✔
71
  }
1✔
72

73
  public XMLConfigBuilder(Class<? extends Configuration> configClass, Reader reader, String environment,
74
      Properties props) {
75
    this(configClass, new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
1✔
76
  }
1✔
77

78
  public XMLConfigBuilder(InputStream inputStream) {
79
    this(inputStream, null, null);
1✔
80
  }
1✔
81

82
  public XMLConfigBuilder(InputStream inputStream, String environment) {
83
    this(inputStream, environment, null);
×
84
  }
×
85

86
  public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {
87
    this(Configuration.class, inputStream, environment, props);
1✔
88
  }
1✔
89

90
  public XMLConfigBuilder(Class<? extends Configuration> configClass, InputStream inputStream, String environment,
91
      Properties props) {
92
    this(configClass, new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);
1✔
93
  }
1✔
94

95
  private XMLConfigBuilder(Class<? extends Configuration> configClass, XPathParser parser, String environment,
96
      Properties props) {
97
    super(newConfig(configClass));
1✔
98
    ErrorContext.instance().resource("SQL Mapper Configuration");
1✔
99
    this.configuration.setVariables(props);
1✔
100
    this.parsed = false;
1✔
101
    this.environment = environment;
1✔
102
    this.parser = parser;
1✔
103
  }
1✔
104

105
  public Configuration parse() {
106
    if (parsed) {
1✔
107
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
1✔
108
    }
109
    parsed = true;
1✔
110
    parseConfiguration(parser.evalNode("/configuration"));
1✔
111
    return configuration;
1✔
112
  }
113

114
  private void parseConfiguration(XNode root) {
115
    try {
116
      // issue #117 read properties first
117
      propertiesElement(root.evalNode("properties"));
1✔
118
      Properties settings = settingsAsProperties(root.evalNode("settings"));
1✔
119
      loadCustomVfsImpl(settings);
1✔
120
      loadCustomLogImpl(settings);
1✔
121
      typeAliasesElement(root.evalNode("typeAliases"));
1✔
122
      pluginsElement(root.evalNode("plugins"));
1✔
123
      objectFactoryElement(root.evalNode("objectFactory"));
1✔
124
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
1✔
125
      reflectorFactoryElement(root.evalNode("reflectorFactory"));
1✔
126
      settingsElement(settings);
1✔
127
      // read it after objectFactory and objectWrapperFactory issue #631
128
      environmentsElement(root.evalNode("environments"));
1✔
129
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
1✔
130
      typeHandlersElement(root.evalNode("typeHandlers"));
1✔
131
      mappersElement(root.evalNode("mappers"));
1✔
132
    } catch (Exception e) {
1✔
133
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
1✔
134
    }
1✔
135
  }
1✔
136

137
  private Properties settingsAsProperties(XNode context) {
138
    if (context == null) {
1✔
139
      return new Properties();
1✔
140
    }
141
    Properties props = context.getChildrenAsProperties();
1✔
142
    // Check that all settings are known to the configuration class
143
    MetaClass metaConfig = MetaClass.forClass(Configuration.class, localReflectorFactory);
1✔
144
    for (Object key : props.keySet()) {
1✔
145
      if (!metaConfig.hasSetter(String.valueOf(key))) {
1✔
146
        throw new BuilderException(
1✔
147
            "The setting " + key + " is not known.  Make sure you spelled it correctly (case sensitive).");
148
      }
149
    }
1✔
150
    return props;
1✔
151
  }
152

153
  private void loadCustomVfsImpl(Properties props) throws ClassNotFoundException {
154
    String value = props.getProperty("vfsImpl");
1✔
155
    if (value == null) {
1!
156
      return;
1✔
157
    }
158
    String[] clazzes = value.split(",");
×
159
    for (String clazz : clazzes) {
×
160
      if (!clazz.isEmpty()) {
×
161
        @SuppressWarnings("unchecked")
162
        Class<? extends VFS> vfsImpl = (Class<? extends VFS>) Resources.classForName(clazz);
×
163
        configuration.setVfsImpl(vfsImpl);
×
164
      }
165
    }
166
  }
×
167

168
  private void loadCustomLogImpl(Properties props) {
169
    Class<? extends Log> logImpl = resolveClass(props.getProperty("logImpl"));
1✔
170
    configuration.setLogImpl(logImpl);
1✔
171
  }
1✔
172

173
  private void typeAliasesElement(XNode context) {
174
    if (context == null) {
1✔
175
      return;
1✔
176
    }
177
    for (XNode child : context.getChildren()) {
1✔
178
      if ("package".equals(child.getName())) {
1✔
179
        String typeAliasPackage = child.getStringAttribute("name");
1✔
180
        configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
1✔
181
      } else {
1✔
182
        String alias = child.getStringAttribute("alias");
1✔
183
        String type = child.getStringAttribute("type");
1✔
184
        try {
185
          Class<?> clazz = Resources.classForName(type);
1✔
186
          if (alias == null) {
1!
187
            typeAliasRegistry.registerAlias(clazz);
×
188
          } else {
189
            typeAliasRegistry.registerAlias(alias, clazz);
1✔
190
          }
191
        } catch (ClassNotFoundException e) {
1✔
192
          throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
1✔
193
        }
1✔
194
      }
195
    }
1✔
196
  }
1✔
197

198
  private void pluginsElement(XNode context) throws Exception {
199
    if (context != null) {
1✔
200
      for (XNode child : context.getChildren()) {
1✔
201
        String interceptor = child.getStringAttribute("interceptor");
1✔
202
        Properties properties = child.getChildrenAsProperties();
1✔
203
        Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).getDeclaredConstructor()
1✔
204
            .newInstance();
1✔
205
        interceptorInstance.setProperties(properties);
1✔
206
        configuration.addInterceptor(interceptorInstance);
1✔
207
      }
1✔
208
    }
209
  }
1✔
210

211
  private void objectFactoryElement(XNode context) throws Exception {
212
    if (context != null) {
1✔
213
      String type = context.getStringAttribute("type");
1✔
214
      Properties properties = context.getChildrenAsProperties();
1✔
215
      ObjectFactory factory = (ObjectFactory) resolveClass(type).getDeclaredConstructor().newInstance();
1✔
216
      factory.setProperties(properties);
1✔
217
      configuration.setObjectFactory(factory);
1✔
218
    }
219
  }
1✔
220

221
  private void objectWrapperFactoryElement(XNode context) throws Exception {
222
    if (context != null) {
1✔
223
      String type = context.getStringAttribute("type");
1✔
224
      ObjectWrapperFactory factory = (ObjectWrapperFactory) resolveClass(type).getDeclaredConstructor().newInstance();
1✔
225
      configuration.setObjectWrapperFactory(factory);
1✔
226
    }
227
  }
1✔
228

229
  private void reflectorFactoryElement(XNode context) throws Exception {
230
    if (context != null) {
1!
231
      String type = context.getStringAttribute("type");
×
232
      ReflectorFactory factory = (ReflectorFactory) resolveClass(type).getDeclaredConstructor().newInstance();
×
233
      configuration.setReflectorFactory(factory);
×
234
    }
235
  }
1✔
236

237
  private void propertiesElement(XNode context) throws Exception {
238
    if (context == null) {
1✔
239
      return;
1✔
240
    }
241
    Properties defaults = context.getChildrenAsProperties();
1✔
242
    String resource = context.getStringAttribute("resource");
1✔
243
    String url = context.getStringAttribute("url");
1✔
244
    if (resource != null && url != null) {
1✔
245
      throw new BuilderException(
1✔
246
          "The properties element cannot specify both a URL and a resource based property file reference.  Please specify one or the other.");
247
    }
248
    if (resource != null) {
1✔
249
      defaults.putAll(Resources.getResourceAsProperties(resource));
1✔
250
    } else if (url != null) {
1✔
251
      defaults.putAll(Resources.getUrlAsProperties(url));
1✔
252
    }
253
    Properties vars = configuration.getVariables();
1✔
254
    if (vars != null) {
1!
255
      defaults.putAll(vars);
×
256
    }
257
    parser.setVariables(defaults);
1✔
258
    configuration.setVariables(defaults);
1✔
259
  }
1✔
260

261
  private void settingsElement(Properties props) {
262
    configuration
1✔
263
        .setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
1✔
264
    configuration.setAutoMappingUnknownColumnBehavior(
1✔
265
        AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));
1✔
266
    configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));
1✔
267
    configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));
1✔
268
    configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));
1✔
269
    configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), false));
1✔
270
    configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));
1✔
271
    configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));
1✔
272
    configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));
1✔
273
    configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));
1✔
274
    configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));
1✔
275
    configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null));
1✔
276
    configuration.setDefaultResultSetType(resolveResultSetType(props.getProperty("defaultResultSetType")));
1✔
277
    configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));
1✔
278
    configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));
1✔
279
    configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));
1✔
280
    configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));
1✔
281
    configuration.setLazyLoadTriggerMethods(
1✔
282
        stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));
1✔
283
    configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));
1✔
284
    configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));
1✔
285
    configuration.setDefaultEnumTypeHandler(resolveClass(props.getProperty("defaultEnumTypeHandler")));
1✔
286
    configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));
1✔
287
    configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true));
1✔
288
    configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false));
1✔
289
    configuration.setLogPrefix(props.getProperty("logPrefix"));
1✔
290
    configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));
1✔
291
    configuration.setShrinkWhitespacesInSql(booleanValueOf(props.getProperty("shrinkWhitespacesInSql"), false));
1✔
292
    configuration.setArgNameBasedConstructorAutoMapping(
1✔
293
        booleanValueOf(props.getProperty("argNameBasedConstructorAutoMapping"), false));
1✔
294
    configuration.setDefaultSqlProviderType(resolveClass(props.getProperty("defaultSqlProviderType")));
1✔
295
    configuration.setNullableOnForEach(booleanValueOf(props.getProperty("nullableOnForEach"), false));
1✔
296
  }
1✔
297

298
  private void environmentsElement(XNode context) throws Exception {
299
    if (context == null) {
1✔
300
      return;
1✔
301
    }
302
    if (environment == null) {
1✔
303
      environment = context.getStringAttribute("default");
1✔
304
    }
305
    for (XNode child : context.getChildren()) {
1!
306
      String id = child.getStringAttribute("id");
1✔
307
      if (isSpecifiedEnvironment(id)) {
1✔
308
        TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
1✔
309
        DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
1✔
310
        DataSource dataSource = dsFactory.getDataSource();
1✔
311
        Environment.Builder environmentBuilder = new Environment.Builder(id).transactionFactory(txFactory)
1✔
312
            .dataSource(dataSource);
1✔
313
        configuration.setEnvironment(environmentBuilder.build());
1✔
314
        break;
1✔
315
      }
316
    }
1✔
317
  }
1✔
318

319
  private void databaseIdProviderElement(XNode context) throws Exception {
320
    if (context == null) {
1✔
321
      return;
1✔
322
    }
323
    String type = context.getStringAttribute("type");
1✔
324
    // awful patch to keep backward compatibility
325
    if ("VENDOR".equals(type)) {
1!
326
      type = "DB_VENDOR";
×
327
    }
328
    Properties properties = context.getChildrenAsProperties();
1✔
329
    DatabaseIdProvider databaseIdProvider = (DatabaseIdProvider) resolveClass(type).getDeclaredConstructor()
1✔
330
        .newInstance();
1✔
331
    databaseIdProvider.setProperties(properties);
1✔
332
    Environment environment = configuration.getEnvironment();
1✔
333
    if (environment != null) {
1!
334
      String databaseId = databaseIdProvider.getDatabaseId(environment.getDataSource());
1✔
335
      configuration.setDatabaseId(databaseId);
1✔
336
    }
337
  }
1✔
338

339
  private TransactionFactory transactionManagerElement(XNode context) throws Exception {
340
    if (context != null) {
1!
341
      String type = context.getStringAttribute("type");
1✔
342
      Properties props = context.getChildrenAsProperties();
1✔
343
      TransactionFactory factory = (TransactionFactory) resolveClass(type).getDeclaredConstructor().newInstance();
1✔
344
      factory.setProperties(props);
1✔
345
      return factory;
1✔
346
    }
347
    throw new BuilderException("Environment declaration requires a TransactionFactory.");
×
348
  }
349

350
  private DataSourceFactory dataSourceElement(XNode context) throws Exception {
351
    if (context != null) {
1!
352
      String type = context.getStringAttribute("type");
1✔
353
      Properties props = context.getChildrenAsProperties();
1✔
354
      DataSourceFactory factory = (DataSourceFactory) resolveClass(type).getDeclaredConstructor().newInstance();
1✔
355
      factory.setProperties(props);
1✔
356
      return factory;
1✔
357
    }
358
    throw new BuilderException("Environment declaration requires a DataSourceFactory.");
×
359
  }
360

361
  private void typeHandlersElement(XNode context) {
362
    if (context == null) {
1✔
363
      return;
1✔
364
    }
365
    for (XNode child : context.getChildren()) {
1✔
366
      if ("package".equals(child.getName())) {
1✔
367
        String typeHandlerPackage = child.getStringAttribute("name");
1✔
368
        typeHandlerRegistry.register(typeHandlerPackage);
1✔
369
      } else {
1✔
370
        String javaTypeName = child.getStringAttribute("javaType");
1✔
371
        String jdbcTypeName = child.getStringAttribute("jdbcType");
1✔
372
        String handlerTypeName = child.getStringAttribute("handler");
1✔
373
        Class<?> javaTypeClass = resolveClass(javaTypeName);
1✔
374
        JdbcType jdbcType = resolveJdbcType(jdbcTypeName);
1✔
375
        Class<?> typeHandlerClass = resolveClass(handlerTypeName);
1✔
376
        if (javaTypeClass != null) {
1✔
377
          if (jdbcType == null) {
1✔
378
            typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
1✔
379
          } else {
380
            typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);
1✔
381
          }
382
        } else {
383
          typeHandlerRegistry.register(typeHandlerClass);
1✔
384
        }
385
      }
386
    }
1✔
387
  }
1✔
388

389
  private void mappersElement(XNode context) throws Exception {
390
    if (context == null) {
1✔
391
      return;
1✔
392
    }
393
    for (XNode child : context.getChildren()) {
1✔
394
      if ("package".equals(child.getName())) {
1✔
395
        String mapperPackage = child.getStringAttribute("name");
1✔
396
        configuration.addMappers(mapperPackage);
1✔
397
      } else {
1✔
398
        String resource = child.getStringAttribute("resource");
1✔
399
        String url = child.getStringAttribute("url");
1✔
400
        String mapperClass = child.getStringAttribute("class");
1✔
401
        if (resource != null && url == null && mapperClass == null) {
1!
402
          ErrorContext.instance().resource(resource);
1✔
403
          try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
1✔
404
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource,
1✔
405
                configuration.getSqlFragments());
1✔
406
            mapperParser.parse();
1✔
407
          }
408
        } else if (resource == null && url != null && mapperClass == null) {
1!
409
          ErrorContext.instance().resource(url);
×
410
          try (InputStream inputStream = Resources.getUrlAsStream(url)) {
×
411
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url,
×
412
                configuration.getSqlFragments());
×
413
            mapperParser.parse();
×
414
          }
415
        } else if (resource == null && url == null && mapperClass != null) {
1!
416
          Class<?> mapperInterface = Resources.classForName(mapperClass);
1✔
417
          configuration.addMapper(mapperInterface);
1✔
418
        } else {
1✔
419
          throw new BuilderException(
×
420
              "A mapper element may only specify a url, resource or class, but not more than one.");
421
        }
422
      }
423
    }
1✔
424
  }
1✔
425

426
  private boolean isSpecifiedEnvironment(String id) {
427
    if (environment == null) {
1!
428
      throw new BuilderException("No environment specified.");
×
429
    }
430
    if (id == null) {
1!
431
      throw new BuilderException("Environment requires an id attribute.");
×
432
    }
433
    return environment.equals(id);
1✔
434
  }
435

436
  private static Configuration newConfig(Class<? extends Configuration> configClass) {
437
    try {
438
      return configClass.getDeclaredConstructor().newInstance();
1✔
439
    } catch (Exception ex) {
1✔
440
      throw new BuilderException("Failed to create a new Configuration instance.", ex);
1✔
441
    }
442
  }
443

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