Reputation: 21
I have a multi-datasource web application with following technique:
And I prefered Java based configuration. Therefore, I have Datasource1Config.java and Datasource2Config.java.
I defined SqlSessionTemplate respectively, and using MapperScannerConfigure to inject my mapper. Following is for datasource1, and the datasource2 just substitute the number.
@Bean(name = "dataSource1MapperScannerConfigurer")
public MapperScannerConfigurer msc() {
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setSqlSessionFactoryBeanName("dataSource1SqlSessionFactory");
msc.setSqlSessionTemplateBeanName("dataSource1SqlSessionFactory");
msc.setBasePackage("demo.mybatisspring.mapper.ds1");
return msc;
}
And then, the error happend
file [C:\...target\classes\demo\mybatisspring\mapper\ds1\UserMapper.class] required a single bean, but 2 were found:
- dataSource1SqlSessionFactory: defined by method 'sqlSessionFactoryBean' in class path resource [demo/mybatisspring/config/DataSource1Config.class]
- dataSource2SqlSessionFactory: defined by method 'sqlSessionFactoryBean2' in class path resource [demo/mybatisspring/config/DataSource2Config.class]
However, if I inject mappers with @MapperScan as following, everything will work fine. (also worked fine when one using @MapperScan and the other using @Bean MapperScannerConfigurer)
@MapperScan(basePackages = "demo.mybatisspring.mapper.ds1", sqlSessionTemplateRef = "dataSource1SqlSessionFactory")
public class DataSource1Config {...}
@MapperScan(basePackages = "demo.mybatisspring.mapper.ds2", sqlSessionTemplateRef = "dataSource2SqlSessionFactory")
public class DataSource2Config {...}
I've tried to trace with debug mode and search so many articles on internet, still can not get the answer instead. So if anyone can help me?
Thanks for your time.
Upvotes: 2
Views: 2345
Reputation: 21
I think answer is here. https://mybatis.org/spring/mappers.html
Scanning for mappers There is no need to register all your mappers one by one. Instead, you can let MyBatis-Spring scan your classpath for them.
There are three different ways to do it:
Using the element. Using the annotation @MapperScan Using a classic Spring xml file and registering the MapperScannerConfigurer Both and @MapperScan are features introduced in MyBatis-Spring 1.2.0. @MapperScan requires Spring 3.1+.
Since 2.0.2, mapper scanning feature support a option (lazy-initialization) that control lazy initialization enabled/disabled of mapper bean. The motivation for adding this option is supporting a lazy initialization control feature supported by Spring Boot 2.2. The default of this option is false (= not use lazy initialization). If developer want to use lazy initialization for mapper bean, it should be set to the true expressly.
Upvotes: 2