应用场景
项目需要同时连接两个不同的数据库A, B,并且它们都为主从架构,一台写库,多台读库。
多数据源
首先要将spring boot自带的DataSourceAutoConfiguration
禁掉,因为它会读取application.properties
文件的spring.datasource.*
属性并自动配置单数据源。在@SpringBootApplication
注解中添加exclude
属性即可:
-
@SpringBootApplication(exclude = {
-
DataSourceAutoConfiguration.class
-
-
public class TitanWebApplication {
-
public static void main(String[] args) {
-
SpringApplication.run(TitanWebApplication.class, args);
-
-
然后在application.properties
中配置多数据源连接信息:
-
-
spring.datasource.titan-master.url=jdbc:mysql:
-
spring.datasource.titan-master.username=
-
spring.datasource.titan-master.password=
-
spring.datasource.titan-master.driver-class-name=com.mysql.jdbc.Driver
-
-
-
-
-
spring.datasource.db2.url=jdbc:mysql:
-
spring.datasource.db2.username=
-
spring.datasource.db2.password=
-
spring.datasource.db2.driver-class-name=com.mysql.jdbc.Driver
由于我们禁掉了自动数据源配置,因些下一步就需要手动将这些数据源创建出来:
-
-
public class DataSourceConfig {
-
-
@Bean(name = "titanMasterDS")
-
-
@ConfigurationProperties(prefix = "spring.datasource.titan-master")
-
public DataSource dataSource1() {
-
return DataSourceBuilder.create().build();
-
-
-
-
-
-
-
@ConfigurationProperties(prefix = "spring.datasource.db2")
-
public DataSource dataSource2() {
-
return DataSourceBuilder.create().build();
-
-
-
接下来需要配置两个mybatis的SqlSessionFactory
分别使用不同的数据源:
-
-
@MapperScan(basePackages = {"titan.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory1")
-
public class MybatisDbAConfig {
-
-
-
@Qualifier("titanMasterDS")
-
-
-
-
-
-
public SqlSessionFactory sqlSessionFactory1() throws Exception {
-
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
-
factoryBean.setDataSource(ds1);
-
-
return factoryBean.getObject();
-
-
-
-
-
-
public SqlSessionTemplate sqlSessionTemplate1() throws Exception {
-
SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory1());
-
-
-
经过上面的配置后,titan.mapper
下的Mapper接口,都会使用titan数据源。同理可配第二个SqlSessionFactory
:
-
-
@MapperScan(basePackages = {"other.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory2")
-
public class MybatisDbBConfig {
-
-
-
-
-
-
public SqlSessionFactory sqlSessionFactory2() throws Exception {
-
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
-
factoryBean.setDataSource(ds2);
-
-
-
return factoryBean.getObject();
-
-
-
-
-
public SqlSessionTemplate sqlSessionTemplate2() throws Exception {
-
SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory2());
-
-
-
完成这些配置后,假设有2个Mapper titan.mapper.UserMapper
和other.mapper.RoleMapper
,使用前者时会自动连接titan库,后者连接ds2库。
补: 上面的用@select @insert注解没有问题,
如果要使用mapper.xml
需要增加下面的配置:
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:path/**/*.xml"));
mybatis 双数据源配置
原文:https://www.cnblogs.com/ddcowboy/p/12285793.html