mybatis配置不同数据源

版本

  • springboot 2.1.6.release
  • mybatis-starter 2.3.0

yaml的写法调整

batis:
  db1:
    jdbcUrl: jdbc:mysql://localhost:3306/test
    username: test
    password: test
    driverClassName: com.mysql.cj.jdbc.Driver
    maximum-pool-size: 20
  db2:
    jdbcUrl: jdbc:mysql://localhost:3307/test
    username: test
    password: test
    driverClassName: com.mysql.cj.jdbc.Driver
    maximum-pool-size: 20
  db3:
  	jdbcUrl: jdbc:mysql://localhost:3308/test
    username: test
    password: test
    driverClassName: com.mysql.cj.jdbc.Driver
    maximum-pool-size: 20

mapper包

有几个数据源就设置几个软件包,如下:

  • com.test.mapper1
  • com.test.mapper2
  • com.test.mapper3

再在resource目录下新建mapper目录,有几个数据源就新建几个子目录,如下:

  • mapper/mapper1
  • mapper/mapper2
  • mapper/mapper3

config

有几个数据源就设置几个config,如下:

/**
 * 仅举一例,其他的照此配置即可
 */
@Configuration
@MapperScan(basePackages = "com.test.mapper1", sqlSessionFactoryRef = "mysqlSessionFactoryOne")
public class DbOneConfig extends MybatisConfig {

	@Bean
    @ConfigurationProperties(prefix = "batis.db1")
    public HikariConfig mysqlHikariConfigOne() {
        return new HikariConfig();
    }

    @Bean(name = "mysqlSessionFactoryOne")
    public SqlSessionFactory sqlSessionFactory(@Autowired @Qualifier("mysqlHikariConfigOne") HikariConfig hikariConfig) throws Exception {
        DataSource dataSource = new HikariDataSource(hikariConfig);
        super.setMapperLocation("classpath:mapper/mapper1/*.xml");
        return this.getSqlSessionFactory(dataSource);
    }
}

使用

在对应的mapper文件夹下写@Mapper文件即可,在service层没有区别,mybatis会把特性掩盖,使得上层调用就像仅有一个数据源一样。
但是在启动类@SpringBootApplication()里面,需要去掉mybatis自动配置:

@SpringBootApplication(exclude = {MybatisAutoConfiguration.class})
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值