Springboot 之整合多个数据源

1.用idea初始化一个springboot项目

包结构如下:

2.具体配置如下:

1.application.yml:

#DataSource
spring:
  datasource:
    test1:
      jdbcUrl: jdbc:mysql://localhost:3306/springbootstudy
      username: root
      password: 1123
      driverClassName : com.mysql.jdbc.Driver
    test2:
      jdbcUrl: jdbc:mysql://localhost:3306/springbootstudy1
      username: root
      password: 1123
      driverClassName : com.mysql.jdbc.Driver

2.DtatasourceConfig:(配置两个数据源方法相同,其中用@Primary指定一个为主数据源,不然启动会报错)

@Configuration
@MapperScan(basePackages = "com.sjy.springbootdemo.domain.repository",sqlSessionFactoryRef = "test1SqlSessionFactory")
public class Datasource1Config {

    @Bean(name = "test1DataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.test1")
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "test1SqlSessionFactory")
    @Primary
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
		bean.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/**/*.xml"));
        return bean.getObject();
    }
}

3.测试成功

service层同时调用两个数据层:

    public Integer addItem(Person person) {
        Integer i1 = personRepository1.addPerson(person);
        Integer i2 = personRepository.addPerson(person);
        return i1+i2;
    }

web层:

@RestController
public class MvcController {
    @Autowired
    private MvcService mvcService;

    @GetMapping(value = "add/item1")
    public String test1(Person person){
        Integer i = mvcService.addItem(person);
        if (i>1){
            return "success";
        }else {
            return "failure";
        }
    }
}

前台访问结果:

后台数据库:

 4.总结

此种方式通过不同数据源用@MapperScan扫描不同的mapper包实现(分包)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值