Add configuration
In application.properties
file add data source configuration1
2
3
4
5
6
7
8
9
10
11spring.datasource.test1.driverClassName=com.mysql.jdbc.Driver
spring.datasource.test1.url=jdbc:mysql://localhost:3306/test1
spring.datasource.test1.username=root
spring.datasource.test1.password=root
spring.datasource.test2.driverClassName=com.mysql.jdbc.Driver
spring.datasource.test2.url=jdbc:mysql://localhost:3306/test2
spring.datasource.test2.username=root
spring.datasource.test2.password=root
mybatis.mapperLocations=classpath:sql-mappers/**/*.xml
Self define data source
New configuration
Point out base package path, sql session reference.1
2
3
4
5
6
"com.burningbright.test1", (basePackages=
sqlSessionFactoryRef="test1SqlSessionFactory")
public class Datasource1 {
...
}
Inject xml path properties
Put mapper xml location into configuration class1
2"${mybatis.mapperLocations}") (
private String mapperLocation;
Add properties holder
1 |
|
Create datasource
1 | "test1Datasource") (name= |
Create session factory
Make sure bean name is same as the class reference annotation1
2
3
4
5
6
7
8
9
10
11"test1SqlSessionFactory") (name=
public SqlSessionFactory testSqlSessionFactory(
@Qualifier("test1Datasource")DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(
new PathMatchingResourcePatternResolver().
getResources(mapperLocation));
return bean.getObject();
}
Create transaction manager bean
1 | "test1TransactionManager") (name= |
Create session template
1 | "test1SqlSessionTemplate") (name= |
Use data source
Add test data source test2 the same as above1
2
3
4
5
6
7
8
"com.burningbright.test1","com.burningbright.test2"}) (basePackages={
public class UserController {
UserMapper userMapper;
...
}
- Prefix must the same as properties keys’ prefix in application.properties
- If
@Primary
not be annotated, application will throw exception.
Unless the reseal framework level has a default primary datasource. @Qualifier
inject object by bean’s name.basePackages
is mapper file’s package path.sqlSessionTemplateRef
is the instance’s reference
https://blog.csdn.net/qq_37142346/article/details/78488452
https://blog.csdn.net/a123demi/article/details/74004499
https://blog.csdn.net/hongweigg/article/details/79104321