1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.spring;
17
18 import javax.sql.DataSource;
19 import java.io.IOException;
20 import java.lang.reflect.Modifier;
21 import java.sql.SQLException;
22 import java.util.HashSet;
23 import java.util.Optional;
24 import java.util.Properties;
25 import java.util.Set;
26 import java.util.stream.Stream;
27
28 import org.apache.ibatis.builder.xml.XMLConfigBuilder;
29 import org.apache.ibatis.builder.xml.XMLMapperBuilder;
30 import org.apache.ibatis.cache.Cache;
31 import org.apache.ibatis.executor.ErrorContext;
32 import org.apache.ibatis.io.Resources;
33 import org.apache.ibatis.io.VFS;
34 import org.apache.ibatis.mapping.DatabaseIdProvider;
35 import org.apache.ibatis.mapping.Environment;
36 import org.apache.ibatis.plugin.Interceptor;
37 import org.apache.ibatis.reflection.factory.ObjectFactory;
38 import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
39 import org.apache.ibatis.scripting.LanguageDriver;
40 import org.apache.ibatis.session.Configuration;
41 import org.apache.ibatis.session.SqlSessionFactory;
42 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
43 import org.apache.ibatis.transaction.TransactionFactory;
44 import org.apache.ibatis.type.TypeHandler;
45 import org.mybatis.logging.Logger;
46 import org.mybatis.logging.LoggerFactory;
47 import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
48 import org.springframework.beans.factory.FactoryBean;
49 import org.springframework.beans.factory.InitializingBean;
50 import org.springframework.context.ApplicationEvent;
51 import org.springframework.context.ApplicationListener;
52 import org.springframework.context.ConfigurableApplicationContext;
53 import org.springframework.context.event.ContextRefreshedEvent;
54 import org.springframework.core.NestedIOException;
55 import org.springframework.core.io.Resource;
56 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
57 import org.springframework.core.io.support.ResourcePatternResolver;
58 import org.springframework.core.type.ClassMetadata;
59 import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
60 import org.springframework.core.type.classreading.MetadataReaderFactory;
61 import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
62 import org.springframework.util.ClassUtils;
63
64 import static org.springframework.util.Assert.notNull;
65 import static org.springframework.util.Assert.state;
66 import static org.springframework.util.ObjectUtils.isEmpty;
67 import static org.springframework.util.StringUtils.hasLength;
68 import static org.springframework.util.StringUtils.tokenizeToStringArray;
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88 public class SqlSessionFactoryBean
89 implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
90
91 private static final Logger LOGGER = LoggerFactory.getLogger(SqlSessionFactoryBean.class);
92
93 private static final ResourcePatternResolver RESOURCE_PATTERN_RESOLVER = new PathMatchingResourcePatternResolver();
94 private static final MetadataReaderFactory METADATA_READER_FACTORY = new CachingMetadataReaderFactory();
95
96 private Resource configLocation;
97
98 private Configuration configuration;
99
100 private Resource[] mapperLocations;
101
102 private DataSource dataSource;
103
104 private TransactionFactory transactionFactory;
105
106 private Properties configurationProperties;
107
108 private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
109
110 private SqlSessionFactory sqlSessionFactory;
111
112
113 private String environment = SqlSessionFactoryBean.class.getSimpleName();
114
115 private boolean failFast;
116
117 private Interceptor[] plugins;
118
119 private TypeHandler<?>[] typeHandlers;
120
121 private String typeHandlersPackage;
122
123 private Class<?>[] typeAliases;
124
125 private String typeAliasesPackage;
126
127 private Class<?> typeAliasesSuperType;
128
129 private LanguageDriver[] scriptingLanguageDrivers;
130
131 private Class<? extends LanguageDriver> defaultScriptingLanguageDriver;
132
133
134 private DatabaseIdProvider databaseIdProvider;
135
136 private Class<? extends VFS> vfs;
137
138 private Cache cache;
139
140 private ObjectFactory objectFactory;
141
142 private ObjectWrapperFactory objectWrapperFactory;
143
144
145
146
147
148
149
150
151 public void setObjectFactory(ObjectFactory objectFactory) {
152 this.objectFactory = objectFactory;
153 }
154
155
156
157
158
159
160
161
162 public void setObjectWrapperFactory(ObjectWrapperFactory objectWrapperFactory) {
163 this.objectWrapperFactory = objectWrapperFactory;
164 }
165
166
167
168
169
170
171
172 public DatabaseIdProvider getDatabaseIdProvider() {
173 return databaseIdProvider;
174 }
175
176
177
178
179
180
181
182
183 public void setDatabaseIdProvider(DatabaseIdProvider databaseIdProvider) {
184 this.databaseIdProvider = databaseIdProvider;
185 }
186
187
188
189
190
191
192 public Class<? extends VFS> getVfs() {
193 return this.vfs;
194 }
195
196
197
198
199
200
201
202 public void setVfs(Class<? extends VFS> vfs) {
203 this.vfs = vfs;
204 }
205
206
207
208
209
210
211 public Cache getCache() {
212 return this.cache;
213 }
214
215
216
217
218
219
220
221 public void setCache(Cache cache) {
222 this.cache = cache;
223 }
224
225
226
227
228
229
230
231
232
233
234 public void setPlugins(Interceptor... plugins) {
235 this.plugins = plugins;
236 }
237
238
239
240
241
242
243
244
245
246
247
248
249
250 public void setTypeAliasesPackage(String typeAliasesPackage) {
251 this.typeAliasesPackage = typeAliasesPackage;
252 }
253
254
255
256
257
258
259
260
261
262
263
264 public void setTypeAliasesSuperType(Class<?> typeAliasesSuperType) {
265 this.typeAliasesSuperType = typeAliasesSuperType;
266 }
267
268
269
270
271
272
273
274
275
276
277
278
279
280 public void setTypeHandlersPackage(String typeHandlersPackage) {
281 this.typeHandlersPackage = typeHandlersPackage;
282 }
283
284
285
286
287
288
289
290
291
292 public void setTypeHandlers(TypeHandler<?>... typeHandlers) {
293 this.typeHandlers = typeHandlers;
294 }
295
296
297
298
299
300
301
302
303
304 public void setTypeAliases(Class<?>... typeAliases) {
305 this.typeAliases = typeAliases;
306 }
307
308
309
310
311
312
313
314
315
316
317 public void setFailFast(boolean failFast) {
318 this.failFast = failFast;
319 }
320
321
322
323
324
325
326
327
328 public void setConfigLocation(Resource configLocation) {
329 this.configLocation = configLocation;
330 }
331
332
333
334
335
336
337
338
339 public void setConfiguration(Configuration configuration) {
340 this.configuration = configuration;
341 }
342
343
344
345
346
347
348
349
350
351
352
353
354 public void setMapperLocations(Resource... mapperLocations) {
355 this.mapperLocations = mapperLocations;
356 }
357
358
359
360
361
362
363
364
365
366 public void setConfigurationProperties(Properties sqlSessionFactoryProperties) {
367 this.configurationProperties = sqlSessionFactoryProperties;
368 }
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388 public void setDataSource(DataSource dataSource) {
389 if (dataSource instanceof TransactionAwareDataSourceProxy) {
390
391
392
393
394 this.dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();
395 } else {
396 this.dataSource = dataSource;
397 }
398 }
399
400
401
402
403
404
405
406
407
408
409
410 public void setSqlSessionFactoryBuilder(SqlSessionFactoryBuilder sqlSessionFactoryBuilder) {
411 this.sqlSessionFactoryBuilder = sqlSessionFactoryBuilder;
412 }
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428 public void setTransactionFactory(TransactionFactory transactionFactory) {
429 this.transactionFactory = transactionFactory;
430 }
431
432
433
434
435
436
437
438
439 public void setEnvironment(String environment) {
440 this.environment = environment;
441 }
442
443
444
445
446
447
448
449
450 public void setScriptingLanguageDrivers(LanguageDriver... scriptingLanguageDrivers) {
451 this.scriptingLanguageDrivers = scriptingLanguageDrivers;
452 }
453
454
455
456
457
458
459
460
461 public void setDefaultScriptingLanguageDriver(Class<? extends LanguageDriver> defaultScriptingLanguageDriver) {
462 this.defaultScriptingLanguageDriver = defaultScriptingLanguageDriver;
463 }
464
465
466
467
468 @Override
469 public void afterPropertiesSet() throws Exception {
470 notNull(dataSource, "Property 'dataSource' is required");
471 notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
472 state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
473 "Property 'configuration' and 'configLocation' can not specified with together");
474
475 this.sqlSessionFactory = buildSqlSessionFactory();
476 }
477
478
479
480
481
482
483
484
485
486
487
488
489 protected SqlSessionFactory buildSqlSessionFactory() throws Exception {
490
491 final Configuration targetConfiguration;
492
493 XMLConfigBuilder xmlConfigBuilder = null;
494 if (this.configuration != null) {
495 targetConfiguration = this.configuration;
496 if (targetConfiguration.getVariables() == null) {
497 targetConfiguration.setVariables(this.configurationProperties);
498 } else if (this.configurationProperties != null) {
499 targetConfiguration.getVariables().putAll(this.configurationProperties);
500 }
501 } else if (this.configLocation != null) {
502 xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
503 targetConfiguration = xmlConfigBuilder.getConfiguration();
504 } else {
505 LOGGER.debug(
506 () -> "Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration");
507 targetConfiguration = new Configuration();
508 Optional.ofNullable(this.configurationProperties).ifPresent(targetConfiguration::setVariables);
509 }
510
511 Optional.ofNullable(this.objectFactory).ifPresent(targetConfiguration::setObjectFactory);
512 Optional.ofNullable(this.objectWrapperFactory).ifPresent(targetConfiguration::setObjectWrapperFactory);
513 Optional.ofNullable(this.vfs).ifPresent(targetConfiguration::setVfsImpl);
514
515 if (hasLength(this.typeAliasesPackage)) {
516 scanClasses(this.typeAliasesPackage, this.typeAliasesSuperType).stream()
517 .filter(clazz -> !clazz.isAnonymousClass()).filter(clazz -> !clazz.isInterface())
518 .filter(clazz -> !clazz.isMemberClass()).forEach(targetConfiguration.getTypeAliasRegistry()::registerAlias);
519 }
520
521 if (!isEmpty(this.typeAliases)) {
522 Stream.of(this.typeAliases).forEach(typeAlias -> {
523 targetConfiguration.getTypeAliasRegistry().registerAlias(typeAlias);
524 LOGGER.debug(() -> "Registered type alias: '" + typeAlias + "'");
525 });
526 }
527
528 if (!isEmpty(this.plugins)) {
529 Stream.of(this.plugins).forEach(plugin -> {
530 targetConfiguration.addInterceptor(plugin);
531 LOGGER.debug(() -> "Registered plugin: '" + plugin + "'");
532 });
533 }
534
535 if (hasLength(this.typeHandlersPackage)) {
536 scanClasses(this.typeHandlersPackage, TypeHandler.class).stream().filter(clazz -> !clazz.isAnonymousClass())
537 .filter(clazz -> !clazz.isInterface()).filter(clazz -> !Modifier.isAbstract(clazz.getModifiers()))
538 .forEach(targetConfiguration.getTypeHandlerRegistry()::register);
539 }
540
541 if (!isEmpty(this.typeHandlers)) {
542 Stream.of(this.typeHandlers).forEach(typeHandler -> {
543 targetConfiguration.getTypeHandlerRegistry().register(typeHandler);
544 LOGGER.debug(() -> "Registered type handler: '" + typeHandler + "'");
545 });
546 }
547
548 if (!isEmpty(this.scriptingLanguageDrivers)) {
549 Stream.of(this.scriptingLanguageDrivers).forEach(languageDriver -> {
550 targetConfiguration.getLanguageRegistry().register(languageDriver);
551 LOGGER.debug(() -> "Registered scripting language driver: '" + languageDriver + "'");
552 });
553 }
554 Optional.ofNullable(this.defaultScriptingLanguageDriver)
555 .ifPresent(targetConfiguration::setDefaultScriptingLanguage);
556
557 if (this.databaseIdProvider != null) {
558 try {
559 targetConfiguration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
560 } catch (SQLException e) {
561 throw new NestedIOException("Failed getting a databaseId", e);
562 }
563 }
564
565 Optional.ofNullable(this.cache).ifPresent(targetConfiguration::addCache);
566
567 if (xmlConfigBuilder != null) {
568 try {
569 xmlConfigBuilder.parse();
570 LOGGER.debug(() -> "Parsed configuration file: '" + this.configLocation + "'");
571 } catch (Exception ex) {
572 throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
573 } finally {
574 ErrorContext.instance().reset();
575 }
576 }
577
578 targetConfiguration.setEnvironment(new Environment(this.environment,
579 this.transactionFactory == null ? new SpringManagedTransactionFactory() : this.transactionFactory,
580 this.dataSource));
581
582 if (this.mapperLocations != null) {
583 if (this.mapperLocations.length == 0) {
584 LOGGER.warn(() -> "Property 'mapperLocations' was specified but matching resources are not found.");
585 } else {
586 for (Resource mapperLocation : this.mapperLocations) {
587 if (mapperLocation == null) {
588 continue;
589 }
590 try {
591 XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
592 targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
593 xmlMapperBuilder.parse();
594 } catch (Exception e) {
595 throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
596 } finally {
597 ErrorContext.instance().reset();
598 }
599 LOGGER.debug(() -> "Parsed mapper file: '" + mapperLocation + "'");
600 }
601 }
602 } else {
603 LOGGER.debug(() -> "Property 'mapperLocations' was not specified.");
604 }
605
606 return this.sqlSessionFactoryBuilder.build(targetConfiguration);
607 }
608
609
610
611
612 @Override
613 public SqlSessionFactory getObject() throws Exception {
614 if (this.sqlSessionFactory == null) {
615 afterPropertiesSet();
616 }
617
618 return this.sqlSessionFactory;
619 }
620
621
622
623
624 @Override
625 public Class<? extends SqlSessionFactory> getObjectType() {
626 return this.sqlSessionFactory == null ? SqlSessionFactory.class : this.sqlSessionFactory.getClass();
627 }
628
629
630
631
632 @Override
633 public boolean isSingleton() {
634 return true;
635 }
636
637
638
639
640 @Override
641 public void onApplicationEvent(ApplicationEvent event) {
642 if (failFast && event instanceof ContextRefreshedEvent) {
643
644 this.sqlSessionFactory.getConfiguration().getMappedStatementNames();
645 }
646 }
647
648 private Set<Class<?>> scanClasses(String packagePatterns, Class<?> assignableType) throws IOException {
649 Set<Class<?>> classes = new HashSet<>();
650 String[] packagePatternArray = tokenizeToStringArray(packagePatterns,
651 ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
652 for (String packagePattern : packagePatternArray) {
653 Resource[] resources = RESOURCE_PATTERN_RESOLVER.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
654 + ClassUtils.convertClassNameToResourcePath(packagePattern) + "/**/*.class");
655 for (Resource resource : resources) {
656 try {
657 ClassMetadata classMetadata = METADATA_READER_FACTORY.getMetadataReader(resource).getClassMetadata();
658 Class<?> clazz = Resources.classForName(classMetadata.getClassName());
659 if (assignableType == null || assignableType.isAssignableFrom(clazz)) {
660 classes.add(clazz);
661 }
662 } catch (Throwable e) {
663 LOGGER.warn(() -> "Cannot load the '" + resource + "'. Cause by " + e.toString());
664 }
665 }
666 }
667 return classes;
668 }
669
670 }