springboot + mybatis 多数据源配置

本文介绍了如何在Springboot项目中使用Mybatis进行多数据源配置,包括配置两个数据源、使用AOP实现动态切换,以及在实际项目中的环境准备、代码实现和测试步骤。
摘要由CSDN通过智能技术生成

前言:

随着应用用户数量的增加,相应的并发请求的数量也会跟着不断增加,慢慢地,单个数据库已经没有办法满足我们频繁的数据库操作请求了,在某些场景下,我们可能会需要配置多个数据源,使用多个数据源(例如实现数据库的读写分离)来缓解系统的压力等,同样的,Springboot官方提供了相应的实现来帮助开发者们配置多数据源,一般分为两种方式(目前我所了解到的),分包和AOP,其中利用AOP实现多个数据源到的动态切换时候会另开一篇文章来写。考虑到mybatis是java开发者们使用较为频繁的数据库框架,所以本篇文章使用Springboot+Mybatis来实现多数据源的配置。

废话不多说,走起。

环境准备

首先新建一个Springboot项目,我这里版本是2.7.10,并在pom文件中引入相关依赖:关键依赖如下:

<parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.7.10</version>
    </parent>


<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

代码部分

1. 多数据源配置

首先呢,在我们Springboot的配置文件中配置我们的datasourse,和以往不一样的是,因为我们有两个数据源,所以要指定相关数据库的名称,其中主数据源为primary,次数据源为secondary如下:

spring:
  datasource:
    primary:
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://127.0.0.1:3306/db1?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
      username: root
      password: 123456
    secondary:
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://127.0.0.1:3306/db2?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
      username: root
      password: 123456

需要我们注意的是,Springboot2.0 在配置数据库连接的时候需要使用jdbc-url,如果只使用url的话会报
jdbcUrl is required with driverClassName.错误。

 新建一个配置类PrimaryDataSourceConfig,用于配置我们的主数据库相关的bean,代码如下:

@Configuration
@MapperScan(basePackages = "com.zhkang.mapper.one", sqlSessionFactoryRef = "PrimarySqlSessionFactory")//basePackages:接口文件的包路径
public class PrimaryDataSourceConfig {
    @Bean(name = "PrimaryDataSource")
    // 表示这个数据源是默认数据源
    @Primary//这个一定要加,如果两个数据源都没有@Primary会报错
    @ConfigurationProperties(prefix = "spring.datasource.primary")//我们配置文件中的前缀
    public DataSource getPrimaryDateSource() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "PrimarySqlSessionFactory")
    @Primary
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("PrimaryDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:com/zhkang/mapper/one/*.xml"));
        return bean.getObject();// 设置mybatis的xml所在位置
    }


    @Bean("PrimarySqlSessionTemplate")
    // 表示这个数据源是默认数据源
    @Primary
    public SqlSessionTemplate primarySqlSessionTemplate(
            @Qualifier("PrimarySqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
}

注解说明:

@MapperScan :配置mybatis的接口类放的地方

@Primary :表示使用的是默认数据库,这个一个要加,否则会因为不知道哪个数据库是默认数据库而报错

@ConfigurationProperties:读取application.properties中的配置参数映射成为一个对象,其中prefix表示参数的前缀

大功告成~ ~ 了吗?并没有,然后配置我们的第二个数据源的配置类,代码如下:

@Configuration
@MapperScan(basePackages = "com.zhkang.mapper.two", sqlSessionFactoryRef = "SecondarySqlSessionFactory")
public class SecondaryDataSourceConfig {
    @Bean(name = "SecondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource getSecondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "SecondarySqlSessionFactory")
    public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("SecondaryDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:com/zhkang/mapper/one/*.xml"));
        return bean.getObject();// 设置mybatis的xml所在位置
    }
    @Bean("SecondarySqlSessionTemplate")
    public SqlSessionTemplate secondarySqlSessionTemplate(
            @Qualifier("SecondarySqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
}

剩下的就是编写我们相应的xml文件和接口类了,代码如下:

@Mapper
@Component
public interface Table1Mapper {
   Table1 selectByPrimaryKey(Integer id);
}

@Mapper
@Component
public interface Table2Mapper {
    Table2 selectByPrimaryKey(Integer id);
}

// 配置文件照日常写就可以,写在各自的xml文件中

注:其中xml文件在本实例中目录为:

测试


    @Autowired
    private Table1Mapper table1Mapper;
       @Autowired
    private Table2Mapper table2Mapper;

       @Test
    public void table2Mapper(){
       Table2 table2 = table2Mapper.selectByPrimaryKey(1);
       System.err.println(table2);
   }

 本文章搬自Springboot +Mybatis实现多数据源配置 - 知乎 (zhihu.com) 大神笔记

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值