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

mybatis / spring / #1071

pending completion
#1071

push

github

web-flow
Merge pull request #786 from mybatis/renovate/spring-batch

Update spring batch to v5.0.1

809 of 905 relevant lines covered (89.39%)

0.89 hits per line

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

88.2
/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java
1
/*
2
 * Copyright 2010-2022 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.mybatis.spring;
17

18
import static org.springframework.util.Assert.notNull;
19
import static org.springframework.util.Assert.state;
20
import static org.springframework.util.ObjectUtils.isEmpty;
21
import static org.springframework.util.StringUtils.hasLength;
22
import static org.springframework.util.StringUtils.tokenizeToStringArray;
23

24
import java.io.IOException;
25
import java.lang.reflect.Modifier;
26
import java.sql.SQLException;
27
import java.util.HashSet;
28
import java.util.Optional;
29
import java.util.Properties;
30
import java.util.Set;
31
import java.util.stream.Stream;
32

33
import javax.sql.DataSource;
34

35
import org.apache.ibatis.builder.xml.XMLConfigBuilder;
36
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
37
import org.apache.ibatis.cache.Cache;
38
import org.apache.ibatis.executor.ErrorContext;
39
import org.apache.ibatis.io.Resources;
40
import org.apache.ibatis.io.VFS;
41
import org.apache.ibatis.mapping.DatabaseIdProvider;
42
import org.apache.ibatis.mapping.Environment;
43
import org.apache.ibatis.plugin.Interceptor;
44
import org.apache.ibatis.reflection.factory.ObjectFactory;
45
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
46
import org.apache.ibatis.scripting.LanguageDriver;
47
import org.apache.ibatis.session.Configuration;
48
import org.apache.ibatis.session.SqlSessionFactory;
49
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
50
import org.apache.ibatis.transaction.TransactionFactory;
51
import org.apache.ibatis.type.TypeHandler;
52
import org.mybatis.logging.Logger;
53
import org.mybatis.logging.LoggerFactory;
54
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
55
import org.springframework.beans.factory.FactoryBean;
56
import org.springframework.beans.factory.InitializingBean;
57
import org.springframework.context.ApplicationEvent;
58
import org.springframework.context.ApplicationListener;
59
import org.springframework.context.ConfigurableApplicationContext;
60
import org.springframework.context.event.ContextRefreshedEvent;
61
import org.springframework.core.io.Resource;
62
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
63
import org.springframework.core.io.support.ResourcePatternResolver;
64
import org.springframework.core.type.ClassMetadata;
65
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
66
import org.springframework.core.type.classreading.MetadataReaderFactory;
67
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
68
import org.springframework.util.ClassUtils;
69

70
/**
71
 * {@code FactoryBean} that creates a MyBatis {@code SqlSessionFactory}. This is the usual way to set up a shared
72
 * MyBatis {@code SqlSessionFactory} in a Spring application context; the SqlSessionFactory can then be passed to
73
 * MyBatis-based DAOs via dependency injection.
74
 * <p>
75
 * Either {@code DataSourceTransactionManager} or {@code JtaTransactionManager} can be used for transaction demarcation
76
 * in combination with a {@code SqlSessionFactory}. JTA should be used for transactions which span multiple databases or
77
 * when container managed transactions (CMT) are being used.
78
 *
79
 * @author Putthiphong Boonphong
80
 * @author Hunter Presnall
81
 * @author Eduardo Macarron
82
 * @author Eddú Meléndez
83
 * @author Kazuki Shimizu
84
 * @author Jens Schauder
85
 *
86
 * @see #setConfigLocation
87
 * @see #setDataSource
88
 */
89
public class SqlSessionFactoryBean
90
    implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
91

92
  private static final Logger LOGGER = LoggerFactory.getLogger(SqlSessionFactoryBean.class);
93

94
  private static final ResourcePatternResolver RESOURCE_PATTERN_RESOLVER = new PathMatchingResourcePatternResolver();
95
  private static final MetadataReaderFactory METADATA_READER_FACTORY = new CachingMetadataReaderFactory();
96

97
  private Resource configLocation;
98

99
  private Configuration configuration;
100

101
  private Resource[] mapperLocations;
102

103
  private DataSource dataSource;
104

105
  private TransactionFactory transactionFactory;
106

107
  private Properties configurationProperties;
108

109
  private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
110

111
  private SqlSessionFactory sqlSessionFactory;
112

113
  // EnvironmentAware requires spring 3.1
114
  private String environment = SqlSessionFactoryBean.class.getSimpleName();
115

116
  private boolean failFast;
117

118
  private Interceptor[] plugins;
119

120
  private TypeHandler<?>[] typeHandlers;
121

122
  private String typeHandlersPackage;
123

124
  @SuppressWarnings("rawtypes")
125
  private Class<? extends TypeHandler> defaultEnumTypeHandler;
126

127
  private Class<?>[] typeAliases;
128

129
  private String typeAliasesPackage;
130

131
  private Class<?> typeAliasesSuperType;
132

133
  private LanguageDriver[] scriptingLanguageDrivers;
134

135
  private Class<? extends LanguageDriver> defaultScriptingLanguageDriver;
136

137
  // issue #19. No default provider.
138
  private DatabaseIdProvider databaseIdProvider;
139

140
  private Class<? extends VFS> vfs;
141

142
  private Cache cache;
143

144
  private ObjectFactory objectFactory;
145

146
  private ObjectWrapperFactory objectWrapperFactory;
147

148
  /**
149
   * Sets the ObjectFactory.
150
   *
151
   * @since 1.1.2
152
   *
153
   * @param objectFactory
154
   *          a custom ObjectFactory
155
   */
156
  public void setObjectFactory(ObjectFactory objectFactory) {
157
    this.objectFactory = objectFactory;
158
  }
159

160
  /**
161
   * Sets the ObjectWrapperFactory.
162
   *
163
   * @since 1.1.2
164
   *
165
   * @param objectWrapperFactory
166
   *          a specified ObjectWrapperFactory
167
   */
168
  public void setObjectWrapperFactory(ObjectWrapperFactory objectWrapperFactory) {
169
    this.objectWrapperFactory = objectWrapperFactory;
170
  }
171

172
  /**
173
   * Gets the DatabaseIdProvider
174
   *
175
   * @since 1.1.0
176
   *
177
   * @return a specified DatabaseIdProvider
178
   */
179
  public DatabaseIdProvider getDatabaseIdProvider() {
180
    return databaseIdProvider;
181
  }
182

183
  /**
184
   * Sets the DatabaseIdProvider. As of version 1.2.2 this variable is not initialized by default.
185
   *
186
   * @since 1.1.0
187
   *
188
   * @param databaseIdProvider
189
   *          a DatabaseIdProvider
190
   */
191
  public void setDatabaseIdProvider(DatabaseIdProvider databaseIdProvider) {
192
    this.databaseIdProvider = databaseIdProvider;
193
  }
194

195
  /**
196
   * Gets the VFS.
197
   *
198
   * @return a specified VFS
199
   */
200
  public Class<? extends VFS> getVfs() {
201
    return this.vfs;
202
  }
203

204
  /**
205
   * Sets the VFS.
206
   *
207
   * @param vfs
208
   *          a VFS
209
   */
210
  public void setVfs(Class<? extends VFS> vfs) {
211
    this.vfs = vfs;
212
  }
213

214
  /**
215
   * Gets the Cache.
216
   *
217
   * @return a specified Cache
218
   */
219
  public Cache getCache() {
220
    return this.cache;
221
  }
222

223
  /**
224
   * Sets the Cache.
225
   *
226
   * @param cache
227
   *          a Cache
228
   */
229
  public void setCache(Cache cache) {
230
    this.cache = cache;
231
  }
232

233
  /**
234
   * Mybatis plugin list.
235
   *
236
   * @since 1.0.1
237
   *
238
   * @param plugins
239
   *          list of plugins
240
   */
241
  public void setPlugins(Interceptor... plugins) {
242
    this.plugins = plugins;
243
  }
244

245
  /**
246
   * Packages to search for type aliases.
247
   * <p>
248
   * Since 2.0.1, allow to specify a wildcard such as {@code com.example.*.model}.
249
   *
250
   * @since 1.0.1
251
   *
252
   * @param typeAliasesPackage
253
   *          package to scan for domain objects
254
   */
255
  public void setTypeAliasesPackage(String typeAliasesPackage) {
256
    this.typeAliasesPackage = typeAliasesPackage;
257
  }
258

259
  /**
260
   * Super class which domain objects have to extend to have a type alias created. No effect if there is no package to
261
   * scan configured.
262
   *
263
   * @since 1.1.2
264
   *
265
   * @param typeAliasesSuperType
266
   *          super class for domain objects
267
   */
268
  public void setTypeAliasesSuperType(Class<?> typeAliasesSuperType) {
269
    this.typeAliasesSuperType = typeAliasesSuperType;
270
  }
271

272
  /**
273
   * Packages to search for type handlers.
274
   * <p>
275
   * Since 2.0.1, allow to specify a wildcard such as {@code com.example.*.typehandler}.
276
   *
277
   * @since 1.0.1
278
   *
279
   * @param typeHandlersPackage
280
   *          package to scan for type handlers
281
   */
282
  public void setTypeHandlersPackage(String typeHandlersPackage) {
283
    this.typeHandlersPackage = typeHandlersPackage;
284
  }
285

286
  /**
287
   * Set type handlers. They must be annotated with {@code MappedTypes} and optionally with {@code MappedJdbcTypes}
288
   *
289
   * @since 1.0.1
290
   *
291
   * @param typeHandlers
292
   *          Type handler list
293
   */
294
  public void setTypeHandlers(TypeHandler<?>... typeHandlers) {
295
    this.typeHandlers = typeHandlers;
296
  }
297

298
  /**
299
   * Set the default type handler class for enum.
300
   *
301
   * @since 2.0.5
302
   *
303
   * @param defaultEnumTypeHandler
304
   *          The default type handler class for enum
305
   */
306
  public void setDefaultEnumTypeHandler(
307
      @SuppressWarnings("rawtypes") Class<? extends TypeHandler> defaultEnumTypeHandler) {
308
    this.defaultEnumTypeHandler = defaultEnumTypeHandler;
309
  }
310

311
  /**
312
   * List of type aliases to register. They can be annotated with {@code Alias}
313
   *
314
   * @since 1.0.1
315
   *
316
   * @param typeAliases
317
   *          Type aliases list
318
   */
319
  public void setTypeAliases(Class<?>... typeAliases) {
320
    this.typeAliases = typeAliases;
321
  }
322

323
  /**
324
   * If true, a final check is done on Configuration to assure that all mapped statements are fully loaded and there is
325
   * no one still pending to resolve includes. Defaults to false.
326
   *
327
   * @since 1.0.1
328
   *
329
   * @param failFast
330
   *          enable failFast
331
   */
332
  public void setFailFast(boolean failFast) {
333
    this.failFast = failFast;
334
  }
335

336
  /**
337
   * Set the location of the MyBatis {@code SqlSessionFactory} config file. A typical value is
338
   * "WEB-INF/mybatis-configuration.xml".
339
   *
340
   * @param configLocation
341
   *          a location the MyBatis config file
342
   */
343
  public void setConfigLocation(Resource configLocation) {
344
    this.configLocation = configLocation;
345
  }
346

347
  /**
348
   * Set a customized MyBatis configuration.
349
   *
350
   * @param configuration
351
   *          MyBatis configuration
352
   *
353
   * @since 1.3.0
354
   */
355
  public void setConfiguration(Configuration configuration) {
356
    this.configuration = configuration;
357
  }
358

359
  /**
360
   * Set locations of MyBatis mapper files that are going to be merged into the {@code SqlSessionFactory} configuration
361
   * at runtime.
362
   * <p>
363
   * This is an alternative to specifying "&lt;sqlmapper&gt;" entries in an MyBatis config file. This property being
364
   * based on Spring's resource abstraction also allows for specifying resource patterns here: e.g.
365
   * "classpath*:sqlmap/*-mapper.xml".
366
   *
367
   * @param mapperLocations
368
   *          location of MyBatis mapper files
369
   */
370
  public void setMapperLocations(Resource... mapperLocations) {
371
    this.mapperLocations = mapperLocations;
372
  }
373

374
  /**
375
   * Set optional properties to be passed into the SqlSession configuration, as alternative to a
376
   * {@code &lt;properties&gt;} tag in the configuration xml file. This will be used to resolve placeholders in the
377
   * config file.
378
   *
379
   * @param sqlSessionFactoryProperties
380
   *          optional properties for the SqlSessionFactory
381
   */
382
  public void setConfigurationProperties(Properties sqlSessionFactoryProperties) {
383
    this.configurationProperties = sqlSessionFactoryProperties;
384
  }
385

386
  /**
387
   * Set the JDBC {@code DataSource} that this instance should manage transactions for. The {@code DataSource} should
388
   * match the one used by the {@code SqlSessionFactory}: for example, you could specify the same JNDI DataSource for
389
   * both.
390
   * <p>
391
   * A transactional JDBC {@code Connection} for this {@code DataSource} will be provided to application code accessing
392
   * this {@code DataSource} directly via {@code DataSourceUtils} or {@code DataSourceTransactionManager}.
393
   * <p>
394
   * The {@code DataSource} specified here should be the target {@code DataSource} to manage transactions for, not a
395
   * {@code TransactionAwareDataSourceProxy}. Only data access code may work with
396
   * {@code TransactionAwareDataSourceProxy}, while the transaction manager needs to work on the underlying target
397
   * {@code DataSource}. If there's nevertheless a {@code TransactionAwareDataSourceProxy} passed in, it will be
398
   * unwrapped to extract its target {@code DataSource}.
399
   *
400
   * @param dataSource
401
   *          a JDBC {@code DataSource}
402
   */
403
  public void setDataSource(DataSource dataSource) {
404
    if (dataSource instanceof TransactionAwareDataSourceProxy) {
405
      // If we got a TransactionAwareDataSourceProxy, we need to perform
406
      // transactions for its underlying target DataSource, else data
407
      // access code won't see properly exposed transactions (i.e.
408
      // transactions for the target DataSource).
409
      this.dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();
410
    } else {
411
      this.dataSource = dataSource;
412
    }
413
  }
414

415
  /**
416
   * Sets the {@code SqlSessionFactoryBuilder} to use when creating the {@code SqlSessionFactory}.
417
   * <p>
418
   * This is mainly meant for testing so that mock SqlSessionFactory classes can be injected. By default,
419
   * {@code SqlSessionFactoryBuilder} creates {@code DefaultSqlSessionFactory} instances.
420
   *
421
   * @param sqlSessionFactoryBuilder
422
   *          a SqlSessionFactoryBuilder
423
   */
424
  public void setSqlSessionFactoryBuilder(SqlSessionFactoryBuilder sqlSessionFactoryBuilder) {
425
    this.sqlSessionFactoryBuilder = sqlSessionFactoryBuilder;
426
  }
427

428
  /**
429
   * Set the MyBatis TransactionFactory to use. Default is {@code SpringManagedTransactionFactory}.
430
   * <p>
431
   * The default {@code SpringManagedTransactionFactory} should be appropriate for all cases: be it Spring transaction
432
   * management, EJB CMT or plain JTA. If there is no active transaction, SqlSession operations will execute SQL
433
   * statements non-transactionally.
434
   * <p>
435
   * <b>It is strongly recommended to use the default {@code TransactionFactory}.</b> If not used, any attempt at
436
   * getting an SqlSession through Spring's MyBatis framework will throw an exception if a transaction is active.
437
   *
438
   * @see SpringManagedTransactionFactory
439
   *
440
   * @param transactionFactory
441
   *          the MyBatis TransactionFactory
442
   */
443
  public void setTransactionFactory(TransactionFactory transactionFactory) {
444
    this.transactionFactory = transactionFactory;
445
  }
446

447
  /**
448
   * <b>NOTE:</b> This class <em>overrides</em> any {@code Environment} you have set in the MyBatis config file. This is
449
   * used only as a placeholder name. The default value is {@code SqlSessionFactoryBean.class.getSimpleName()}.
450
   *
451
   * @param environment
452
   *          the environment name
453
   */
454
  public void setEnvironment(String environment) {
455
    this.environment = environment;
456
  }
457

458
  /**
459
   * Set scripting language drivers.
460
   *
461
   * @param scriptingLanguageDrivers
462
   *          scripting language drivers
463
   *
464
   * @since 2.0.2
465
   */
466
  public void setScriptingLanguageDrivers(LanguageDriver... scriptingLanguageDrivers) {
467
    this.scriptingLanguageDrivers = scriptingLanguageDrivers;
468
  }
469

470
  /**
471
   * Set a default scripting language driver class.
472
   *
473
   * @param defaultScriptingLanguageDriver
474
   *          A default scripting language driver class
475
   *
476
   * @since 2.0.2
477
   */
478
  public void setDefaultScriptingLanguageDriver(Class<? extends LanguageDriver> defaultScriptingLanguageDriver) {
479
    this.defaultScriptingLanguageDriver = defaultScriptingLanguageDriver;
480
  }
481

482
  /**
483
   * {@inheritDoc}
484
   */
485
  @Override
486
  public void afterPropertiesSet() throws Exception {
487
    notNull(dataSource, "Property 'dataSource' is required");
488
    notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
489
    state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
490
        "Property 'configuration' and 'configLocation' can not specified with together");
491

492
    this.sqlSessionFactory = buildSqlSessionFactory();
493
  }
494

495
  /**
496
   * Build a {@code SqlSessionFactory} instance.
497
   * <p>
498
   * The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a
499
   * {@code SqlSessionFactory} instance based on a Reader. Since 1.3.0, it can be specified a {@link Configuration}
500
   * instance directly(without config file).
501
   *
502
   * @return SqlSessionFactory
503
   *
504
   * @throws Exception
505
   *           if configuration is failed
506
   */
507
  protected SqlSessionFactory buildSqlSessionFactory() throws Exception {
508

509
    final Configuration targetConfiguration;
510

511
    XMLConfigBuilder xmlConfigBuilder = null;
512
    if (this.configuration != null) {
513
      targetConfiguration = this.configuration;
514
      if (targetConfiguration.getVariables() == null) {
515
        targetConfiguration.setVariables(this.configurationProperties);
516
      } else if (this.configurationProperties != null) {
517
        targetConfiguration.getVariables().putAll(this.configurationProperties);
518
      }
519
    } else if (this.configLocation != null) {
520
      xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
521
      targetConfiguration = xmlConfigBuilder.getConfiguration();
522
    } else {
523
      LOGGER.debug(
524
          () -> "Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration");
525
      targetConfiguration = new Configuration();
526
      Optional.ofNullable(this.configurationProperties).ifPresent(targetConfiguration::setVariables);
527
    }
528

529
    Optional.ofNullable(this.objectFactory).ifPresent(targetConfiguration::setObjectFactory);
530
    Optional.ofNullable(this.objectWrapperFactory).ifPresent(targetConfiguration::setObjectWrapperFactory);
531
    Optional.ofNullable(this.vfs).ifPresent(targetConfiguration::setVfsImpl);
532

533
    if (hasLength(this.typeAliasesPackage)) {
534
      scanClasses(this.typeAliasesPackage, this.typeAliasesSuperType).stream()
535
          .filter(clazz -> !clazz.isAnonymousClass()).filter(clazz -> !clazz.isInterface())
536
          .filter(clazz -> !clazz.isMemberClass()).forEach(targetConfiguration.getTypeAliasRegistry()::registerAlias);
537
    }
538

539
    if (!isEmpty(this.typeAliases)) {
540
      Stream.of(this.typeAliases).forEach(typeAlias -> {
541
        targetConfiguration.getTypeAliasRegistry().registerAlias(typeAlias);
542
        LOGGER.debug(() -> "Registered type alias: '" + typeAlias + "'");
543
      });
544
    }
545

546
    if (!isEmpty(this.plugins)) {
547
      Stream.of(this.plugins).forEach(plugin -> {
548
        targetConfiguration.addInterceptor(plugin);
549
        LOGGER.debug(() -> "Registered plugin: '" + plugin + "'");
550
      });
551
    }
552

553
    if (hasLength(this.typeHandlersPackage)) {
554
      scanClasses(this.typeHandlersPackage, TypeHandler.class).stream().filter(clazz -> !clazz.isAnonymousClass())
555
          .filter(clazz -> !clazz.isInterface()).filter(clazz -> !Modifier.isAbstract(clazz.getModifiers()))
556
          .forEach(targetConfiguration.getTypeHandlerRegistry()::register);
557
    }
558

559
    if (!isEmpty(this.typeHandlers)) {
560
      Stream.of(this.typeHandlers).forEach(typeHandler -> {
561
        targetConfiguration.getTypeHandlerRegistry().register(typeHandler);
562
        LOGGER.debug(() -> "Registered type handler: '" + typeHandler + "'");
563
      });
564
    }
565

566
    targetConfiguration.setDefaultEnumTypeHandler(defaultEnumTypeHandler);
567

568
    if (!isEmpty(this.scriptingLanguageDrivers)) {
569
      Stream.of(this.scriptingLanguageDrivers).forEach(languageDriver -> {
570
        targetConfiguration.getLanguageRegistry().register(languageDriver);
571
        LOGGER.debug(() -> "Registered scripting language driver: '" + languageDriver + "'");
572
      });
573
    }
574
    Optional.ofNullable(this.defaultScriptingLanguageDriver)
575
        .ifPresent(targetConfiguration::setDefaultScriptingLanguage);
576

577
    if (this.databaseIdProvider != null) {// fix #64 set databaseId before parse mapper xmls
578
      try {
579
        targetConfiguration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
580
      } catch (SQLException e) {
581
        throw new IOException("Failed getting a databaseId", e);
582
      }
583
    }
584

585
    Optional.ofNullable(this.cache).ifPresent(targetConfiguration::addCache);
586

587
    if (xmlConfigBuilder != null) {
588
      try {
589
        xmlConfigBuilder.parse();
590
        LOGGER.debug(() -> "Parsed configuration file: '" + this.configLocation + "'");
591
      } catch (Exception ex) {
592
        throw new IOException("Failed to parse config resource: " + this.configLocation, ex);
593
      } finally {
594
        ErrorContext.instance().reset();
595
      }
596
    }
597

598
    targetConfiguration.setEnvironment(new Environment(this.environment,
599
        this.transactionFactory == null ? new SpringManagedTransactionFactory() : this.transactionFactory,
600
        this.dataSource));
601

602
    if (this.mapperLocations != null) {
603
      if (this.mapperLocations.length == 0) {
604
        LOGGER.warn(() -> "Property 'mapperLocations' was specified but matching resources are not found.");
605
      } else {
606
        for (Resource mapperLocation : this.mapperLocations) {
607
          if (mapperLocation == null) {
608
            continue;
609
          }
610
          try {
611
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
612
                targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
613
            xmlMapperBuilder.parse();
614
          } catch (Exception e) {
615
            throw new IOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
616
          } finally {
617
            ErrorContext.instance().reset();
618
          }
619
          LOGGER.debug(() -> "Parsed mapper file: '" + mapperLocation + "'");
620
        }
621
      }
622
    } else {
623
      LOGGER.debug(() -> "Property 'mapperLocations' was not specified.");
624
    }
625

626
    return this.sqlSessionFactoryBuilder.build(targetConfiguration);
627
  }
628

629
  /**
630
   * {@inheritDoc}
631
   */
632
  @Override
633
  public SqlSessionFactory getObject() throws Exception {
634
    if (this.sqlSessionFactory == null) {
635
      afterPropertiesSet();
636
    }
637

638
    return this.sqlSessionFactory;
639
  }
640

641
  /**
642
   * {@inheritDoc}
643
   */
644
  @Override
645
  public Class<? extends SqlSessionFactory> getObjectType() {
646
    return this.sqlSessionFactory == null ? SqlSessionFactory.class : this.sqlSessionFactory.getClass();
647
  }
648

649
  /**
650
   * {@inheritDoc}
651
   */
652
  @Override
653
  public boolean isSingleton() {
654
    return true;
655
  }
656

657
  /**
658
   * {@inheritDoc}
659
   */
660
  @Override
661
  public void onApplicationEvent(ApplicationEvent event) {
662
    if (failFast && event instanceof ContextRefreshedEvent) {
663
      // fail-fast -> check all statements are completed
664
      this.sqlSessionFactory.getConfiguration().getMappedStatementNames();
665
    }
666
  }
667

668
  private Set<Class<?>> scanClasses(String packagePatterns, Class<?> assignableType) throws IOException {
669
    Set<Class<?>> classes = new HashSet<>();
670
    String[] packagePatternArray = tokenizeToStringArray(packagePatterns,
671
        ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
672
    for (String packagePattern : packagePatternArray) {
673
      Resource[] resources = RESOURCE_PATTERN_RESOLVER.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
674
          + ClassUtils.convertClassNameToResourcePath(packagePattern) + "/**/*.class");
675
      for (Resource resource : resources) {
676
        try {
677
          ClassMetadata classMetadata = METADATA_READER_FACTORY.getMetadataReader(resource).getClassMetadata();
678
          Class<?> clazz = Resources.classForName(classMetadata.getClassName());
679
          if (assignableType == null || assignableType.isAssignableFrom(clazz)) {
680
            classes.add(clazz);
681
          }
682
        } catch (Throwable e) {
683
          LOGGER.warn(() -> "Cannot load the '" + resource + "'. Cause by " + e.toString());
684
        }
685
      }
686
    }
687
    return classes;
688
  }
689

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