springboot mybatis/mybatis-plus 多數據源配置


最近需要在一個模塊里使用兩個數據庫,因此要進行多數據源配置,此外,項目本身在用mybatis-plus,此處記錄兩種配置方法

一 springboot mybatis 多數據源

這種方法主要進行springboot mybatis 多數據源的配置,不適用於mybatis-plus,使用的是配置類的方法

1 數據庫配置文件


spring:
  datasource:
    test1:
        jdbc-url: jdbc:mysql://localhost:3306/alice_test?serverTimezone=CTT&useUnicode=true&characterEncoding=utf8
        driverClassName: com.mysql.cj.jdbc.Driver
        username: root
        password: xxx
    test2:
        jdbc-url: jdbc:mysql://localhost:3306/alice_test_two?serverTimezone=CTT&useUnicode=true&characterEncoding=utf8
        driverClassName: com.mysql.cj.jdbc.Driver
        username: root
        password: xxx
 
mybatis:
  mapper-locations: classpath:*/mapper/**.xml

注意事項:url修改為jdbc-url,在單數據源配置中,使用的是url,不是jdbc-url。多數據源配置中使用url啟動會報錯(看版本)

2 配置類

主數據源配置類:

package com.alice.springboot.config;
 
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
 
import javax.sql.DataSource;
 
@Configuration
@MapperScan(basePackages = "com.alice.springboot.mapper.test", sqlSessionFactoryRef = "test1SqlSessionFactory")
public class DataSourceConfig1 {
 
    // 將這個對象放入Spring容器中
    @Bean(name = "test1DataSource")
    // 表示這個數據源是默認數據源
    @Primary
    // 讀取application.properties中的配置參數映射成為一個對象
    // prefix表示參數的前綴
    @ConfigurationProperties(prefix = "spring.datasource.test1")
    public DataSource getDateSource1()
    {
        return DataSourceBuilder.create().build();
    }
 
    @Bean(name = "test1SqlSessionFactory")
    // 表示這個數據源是默認數據源
    @Primary
    // @Qualifier表示查找Spring容器中名字為test1DataSource的對象
    public SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1DataSource") DataSource datasource)
            throws Exception
    {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 設置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/test/*.xml"));
        return bean.getObject();
    }
 
    @Bean("test1SqlSessionTemplate")
    // 表示這個數據源是默認數據源
    @Primary
    public SqlSessionTemplate test1SqlSessionTemplate(
            @Qualifier("test1SqlSessionFactory") SqlSessionFactory sessionFactory)
    {
        return new SqlSessionTemplate(sessionFactory);
    }
}

次數據源配置類:

package com.alice.springboot.config;
 
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
 
import javax.sql.DataSource;
 
@Configuration
@MapperScan(basePackages = "com.alice.springboot.mapper.testTwo", sqlSessionFactoryRef = "test2SqlSessionFactory")
public class DataSourceConfig2 {
    @Bean(name = "test2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test2")
    public DataSource getDateSource2()
    {
        return DataSourceBuilder.create().build();
    }
 
    @Bean(name = "test2SqlSessionFactory")
    public SqlSessionFactory test2SqlSessionFactory(@Qualifier("test2DataSource") DataSource datasource)
            throws Exception
    {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/testTwo/*.xml"));
        return bean.getObject();
    }
 
    @Bean("test2SqlSessionTemplate")
    public SqlSessionTemplate test2SqlSessionTemplate(
            @Qualifier("test2SqlSessionFactory") SqlSessionFactory sessionFactory)
    {
        return new SqlSessionTemplate(sessionFactory);
    }
}

3 啟動類——啟動類需要取消加載數據源自動配置


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
 
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
//@MapperScan("com.alice.springboot.mapper.*")
public class AliceApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(AliceApplication.class, args);
    }
 
}

二 springboot mybatis-plus 多數據源(推薦)

引入“dynamic-datasource-spring-boot-starter”依賴,在yml中配置后,在使用從數據源的mapper上添加注釋即可,非常方便。

1 項目結構

2 引入依賴(僅僅與mybatis-plus相關的,版本實測可用)

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

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>2.5.4</version>
        </dependency>

3 編寫配置

application.yml

spring:
  mvc:
    static-path-pattern: /road/**
  resources:
    static-locations: file:${file.address.prefix}
  jackson:
    time-zone: GMT+8
    date-format: yyyy-MM-dd HH:mm:ss
  datasource:
    dynamic:
      primary: master #設置默認的數據源或者數據源組,默認值即為master,如果讀者只是單數據源只需要注釋掉slave相關配置即可,這里為了方便演示master與slave保持相同
      datasource:
        master:
          url: jdbc:postgresql://192.168.0.22:5432/ees_pdjgzx
          username: pdjgzx
          password: pdjgzx@sa
          driver-class-name: org.postgresql.Driver
        slave:
          url: jdbc:postgresql://192.168.0.22:5432/sys_authorization
          username: slifesys
          password: slifesyssa
          driver-class-name: org.postgresql.Driver
      initial-size: 10 # 以下是連接池配置
      max-active: 100
      min-idle: 10
      max-wait: 60000
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      #validation-query: SELECT 1
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        login-username: druid
        login-password: 123456
      filter:
        stat:
          log-slow-sql: true
          slow-sql-millis: 1000
          merge-sql: false
        wall:
          config:
            multi-statement-allow: true

#mybatis plus
mybatis-plus:
  mapper-locations: classpath:mapper/*/*.xml
  #實體掃描,多個package用逗號或者分號分隔
  typeAliasesPackage: com.roadclean.api.*.*.entity
  check-config-location: true
  configuration:
    #是否開啟自動駝峰命名規則(camel case)映射
    map-underscore-to-camel-case: true
    #全局地開啟或關閉配置文件中的所有映射器已經配置的任何緩存
    cache-enabled: false
    call-setters-on-nulls: true
    #配置JdbcTypeForNull, oracle數據庫必須配置
    jdbc-type-for-null: 'null'
    #MyBatis 自動映射時未知列或未知屬性處理策略 NONE:不做任何處理 (默認值), WARNING:以日志的形式打印相關警告信息, FAILING:當作映射失敗處理,並拋出異常和詳細信息
    auto-mapping-unknown-column-behavior: warning
  global-config:
    banner: false
    db-config:
      #主鍵類型  0:"數據庫ID自增", 1:"未設置主鍵類型",2:"用戶輸入ID (該類型可以通過自己注冊自動填充插件進行填充)", 3:"全局唯一ID (idWorker), 4:全局唯一ID (UUID), 5:字符串全局唯一ID (idWorker 的字符串表示)";
      id-type: UUID
      #字段驗證策略 IGNORED:"忽略判斷", NOT_NULL:"非NULL判斷", NOT_EMPTY:"非空判斷", DEFAULT 默認的,一般只用於注解里(1. 在全局里代表 NOT_NULL,2. 在注解里代表 跟隨全局)
      field-strategy: NOT_EMPTY
      #數據庫大寫下划線轉換
      capital-mode: true
      #邏輯刪除值
      logic-delete-value: 0
      #邏輯未刪除值
      logic-not-delete-value: 1

4 啟動類

@SpringBootApplication
@MapperScan("com.roadclean.api.*.mapper")
public class RoadcleanApplication {
    public static void main(String[] args) {
        SpringApplication.run(RoadcleanApplication.class,args);
    }
}

5 使用注釋

使用主數據源的mapper不用管,在使用從數據源的mapper(interface)上添加注釋

package com.roadclean.api.roadclean.mapper;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.roadclean.api.roadclean.entity.SysDepartmentinfo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;


@DS("slave")
public interface SysDepartmentinfoMapper extends BaseMapper<SysDepartmentinfo> {

}

6 使用mapper

在service里使用mapper,主從數據源一致,注入后使用方法即可。

@Service
public class RoadCleanScenesServiceImpl implements RoadCleanScenesService {

    @Autowired
    private BaseMatunitinfoMapper baseMatunitinfoMapper;
    @Autowired
    private SysDepartmentinfoMapper sysDepartmentinfoMapper;

    @Override
    public Map<String, Object> getIndustryOverview() {

        Map<String, Object> map = new HashMap<>();
        List<BaseMatunitinfo> dataMList = new ArrayList<>();

        dataMList = baseMatunitinfoMapper.selectListt();

        List<SysDepartmentinfo> dataDList = new ArrayList<>();
        dataDList =  sysDepartmentinfoMapper.selectList(new QueryWrapper<>());


        map.put("m", dataMList);
        map.put("d", dataDList);

        return map;
    }
}

參考:https://blog.csdn.net/m0_37872413/article/details/91352507
https://blog.csdn.net/belonghuang157405/article/details/89708851


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM