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);
	}
}
经验分享 程序员 微信小程序 职场和发展