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
(basePackages="com.burningbright.test1",
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 | (name="test1Datasource") |
Create session factory
Make sure bean name is same as the class reference annotation1
2
3
4
5
6
7
8
9
10
11(name="test1SqlSessionFactory")
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 | (name="test1TransactionManager") |
Create session template
1 | (name="test1SqlSessionTemplate") |
Use data source
Add test data source test2 the same as above1
2
3
4
5
6
7
8
(basePackages={"com.burningbright.test1","com.burningbright.test2"})
public class UserController {
UserMapper userMapper;
...
}
- Prefix must the same as properties keys’ prefix in application.properties
- If
@Primarynot be annotated, application will throw exception.
Unless the reseal framework level has a default primary datasource. @Qualifierinject object by bean’s name.basePackagesis mapper file’s package path.sqlSessionTemplateRefis 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