springboot+mybatisPlus+durid集成双数据源

1.依赖

<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>

2.yml配置

# THYMELEAF (ThymeleafAutoConfiguration)
#开启模板缓存(默认值:true)
spring:
   datasource:
     type: com.alibaba.druid.pool.DruidDataSource
     druid:
       master:
         driver-class-name: xxxxxxxx
         url: xxxxxxxx
         username: xxxxxxxx
         password: xxxxxxxx
         slaver:
         driver-class-name: xxxxxxxx
         url: xxxxxxxx
         username: xxxxxxxx
         password: xxxxxxxx
   thymeleaf:
     #开启MVC Thymeleaf视图解析(默认值:true)
     enabled: true
     cache: false
     check-template: true
     #检查模板位置是否正确(默认值:true)
     check-template-location: true
     #Content-Type的值(默认值:text/html)
     servlet:
       content-type: text/html
     #模板编码
     encoding: UTF-8
     #模板類型
     mode: LEGACYHTML5
    #在构建URL时添加到视图名称前的前缀(默认值:classpath:/templates/)
     prefix: classpath:/templates/
    #在构建URL时添加到视图名称后的后缀(默认值:.html)
     suffix: .html
mybatis-plus:
  type-aliases-package: com.xxxxxx.entity
  global-config:
    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 1
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 2
    #驼峰下划线转换
    db-column-underline: true
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    #驼峰转下划线
    map-underscore-to-camel-case: true
    #关闭缓存
    cache-enabled: false
    #表地段记录为null时候返回null
    call-setters-on-nulls: true

logging:
   config: classpath:logback-spring.xml
server:
  port: 8989

3.创建数据源配置config

创建第一个数据源的配置类


@Configuration
@MapperScan(basePackages = "com.xxxxx.mapper.master", sqlSessionTemplateRef  = "masterSqlSessionTemplate")
public class MasterDataSourceConfiguration {
		@Value("${spring.datasource.druid.master.driver-class-name}")
	    private String driverClassName;

	    @Value("${spring.datasource.druid.master.url}")
	    private String url;

	    @Value("${spring.datasource.druid.master.username}")
	    private String username;

	    @Value("${spring.datasource.druid.master.password}")
	    private String password;

	    @Bean(name = "masterDataSource")
	    @Primary
	    public DataSource dataSource() {
	        DruidDataSource dataSource = new DruidDataSource();
	        dataSource.setDriverClassName(this.driverClassName);
	        dataSource.setUrl(this.url);
	        dataSource.setUsername(this.username);
	        dataSource.setPassword(this.password);
	        return dataSource;
	    }

	    @Bean(name = "masterSqlSessionFactory")
	    @Primary
	    public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
	       try {
	    	   MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
	        bean.setDataSource(dataSource);
	        bean.setPlugins(new Interceptor[]{ new PaginationInterceptor() });
	        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*/*.xml"));
	        return bean.getObject();
        }catch(Exception e) {
        	return null;
        }
	    }

	    @Bean(name = "masterTransactionManager")
	    @Primary
	    public DataSourceTransactionManager transactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
	        return new DataSourceTransactionManager(dataSource);
	    }

	    @Bean(name = "masterSqlSessionTemplate")
	    @Primary
	    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
	        try {
	    	return new SqlSessionTemplate(sqlSessionFactory);
	        }catch(Exception e) {
	        	return null;
	        }
	    }
	}

创建第二个数据源的配置类


@Configuration
@MapperScan(basePackages = "com.xxxxx.mapper.slaver", sqlSessionTemplateRef  = "slaverSqlSessionTemplate")
public class SlaverDataSourceConfiguration {
	@Value("${spring.datasource.druid.slaver.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.druid.slaver.url}")
    private String url;

    @Value("${spring.datasource.druid.slaver.username}")
    private String username;

    @Value("${spring.datasource.druid.slaver.password}")
    private String password;


    @Bean(name = "slaverDataSource")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(this.driverClassName);
        dataSource.setUrl(this.url);
        dataSource.setUsername(this.username);
        dataSource.setPassword(this.password);
        return dataSource;
    }

    @Bean(name = "slaverSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("slaverDataSource") DataSource dataSource) throws Exception {
        try {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setPlugins(new Interceptor[]{ new PaginationInterceptor() });
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*/*.xml"));
        return bean.getObject();
        }catch(Exception e) {
        	return null;
        }
    }

    @Bean(name = "slaverTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("slaverDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "slaverSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("slaverSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
    	 try {
    	return new SqlSessionTemplate(sqlSessionFactory);
         }catch(Exception e) {
         	return null;
         }
    }
}

只需要将mapper映射接口放入指定的包下,就访问指定的数据库,多个数据源以此类推

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值