MyBaits多数据源配置

环境及依赖

首先准备一个SpringBoot项目,主要依赖如下:

		<parent>
        	<groupId>org.springframework.boot</groupId>
        	<artifactId>spring-boot-starter-parent</artifactId>
        	<version>2.2.2.RELEASE</version>
        	<relativePath/> <!-- lookup parent from repository -->
    	</parent>
    
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

具体代码

  • 配置文件

    ####注意是jdbc-url而不是url,不然会报错:Cause: java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.
    
    spring:
      datasource:
        primary:
          driver-class-name: com.mysql.cj.jdbc.Driver
          jdbc-url: jdbc:mysql://localhost:3306/executor?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
          username: root
          password: root
        secondary:
          driver-class-name: com.mysql.cj.jdbc.Driver
          jdbc-url: jdbc:mysql://localhost:3306/halo_dev?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
          username: root
          password: root
    
  • 新建一个配置类,用于配置主数据库相关的bean。

    • 第一个数据源

      /**
       * @author 晓果冻
       * @version 1.0
       * @date 2021/10/24 15:39
       */
      @Configuration
      //basePackages是接口路径
      @MapperScan(basePackages = "com.cgd.xxljobexecutor.dao.executor", 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);
              //这里需要mybatis的xml的路径
              bean.setMapperLocations(
                      new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/executor/*.xml"));
              return bean.getObject();// 设置mybatis的xml所在位置
          }
      
          @Bean("PrimarySqlSessionTemplate")
          // 表示这个数据源是默认数据源
          @Primary
          public SqlSessionTemplate primarySqlSessionTemplate(
                  @Qualifier("PrimarySqlSessionFactory") SqlSessionFactory sessionfactory) {
              return new SqlSessionTemplate(sessionfactory);
          }
      }
      
    • 第二个数据源配置

      /**
       * @author 晓果冻
       * @version 1.0
       * @date 2021/10/24 15:41
       */
      @Configuration
      @MapperScan(basePackages = "com.cgd.xxljobexecutor.dao.halo", 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*:mapper/halo/*.xml"));
              return bean.getObject();// 设置mybatis的xml所在位置
          }
      
          @Bean("SecondarySqlSessionTemplate")
          public SqlSessionTemplate secondarySqlSessionTemplate(
                  @Qualifier("SecondarySqlSessionFactory") SqlSessionFactory sessionfactory) {
              return new SqlSessionTemplate(sessionfactory);
          }
      }
      

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

    @Primary :默认数据库,否则会因为不知道哪个数据库是默认数据库而报错。

  • 项目结构
    image-20211024161628283

相关代码仓库https://gitee.com/cgd0526/xxl-job-executor

Q.E.D.


一个热爱生活的95后精神小伙