溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

springboot 中怎么利用mybatis 配置多數(shù)據(jù)源

發(fā)布時(shí)間:2021-06-18 16:17:09 來(lái)源:億速云 閱讀:184 作者:Leah 欄目:大數(shù)據(jù)

今天就跟大家聊聊有關(guān)springboot 中怎么利用mybatis 配置多數(shù)據(jù)源,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

一、項(xiàng)目啟動(dòng)成功后創(chuàng)建bean的方式

pom.xml

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid-spring-boot-starter</artifactId>
   <version>1.1.10</version>
</dependency>

<!-- maven倉(cāng)庫(kù)中沒(méi)有oracle數(shù)據(jù)庫(kù)驅(qū)動(dòng),這里將jar 放到工程下進(jìn)行引入 -->
<dependency>
  <groupId>com.ojdbc</groupId>
  <artifactId>ojdbc</artifactId>
  <version>10.2.0.1</version>
  <scope>system</scope>
  <systemPath>${project.basedir}/src/main/lib/ojdbc14-10.2.0.1.0.jar</systemPath>
</dependency>

 <dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.38</version>
</dependency>

application.properties

#oracle數(shù)據(jù)庫(kù)
spring.datasource.master.url=jdbc:oracle:thin:@localhost:1521:test
spring.datasource.master.username=oracle
spring.datasource.master.password=123456
spring.datasource.master.driverClassName=oracle.jdbc.OracleDriver
spring.datasource.master.initialSize=5
spring.datasource.master.maxActive=15
spring.datasource.master.minIdle=5
spring.datasource.master.poolPreparedStatements=true
spring.datasource.master.validationQuery=SELECT 1 FROM DUAL
#配置執(zhí)行多條sql比如:批量處理
#對(duì)應(yīng)的錯(cuò)誤:sql injection violation, multi-statement not allow
spring.datasource.master.wall.multiStatementAllow=true
#配置執(zhí)行特殊sql比如sql server的創(chuàng)建臨時(shí)表(declare)語(yǔ)句
#對(duì)應(yīng)的錯(cuò)誤:sql injection violation, class com.alibaba.druid.sql.ast.statement.SQLDeclareStatement not allow
spring.datasource.master.wall.noneBaseStatementAllow=true

#mysql數(shù)據(jù)庫(kù)
spring.datasource.slave.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8
spring.datasource.slave.username=mysql
spring.datasource.slave.password=123456
spring.datasource.slave.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.slave.initialSize=5
spring.datasource.slave.maxActive=15
spring.datasource.slave.minIdle=5
spring.datasource.slave.poolPreparedStatements=true
spring.datasource.slave.validationQuery=SELECT 1
#配置執(zhí)行多條sql比如:批量處理
#對(duì)應(yīng)的錯(cuò)誤:sql injection violation, multi-statement not allow
spring.datasource.master.wall.multiStatementAllow=true
#配置執(zhí)行特殊sql比如sql server的創(chuàng)建臨時(shí)表(declare)語(yǔ)句
#對(duì)應(yīng)的錯(cuò)誤:sql injection violation, class com.alibaba.druid.sql.ast.statement.SQLDeclareStatement not allow
spring.datasource.master.wall.noneBaseStatementAllow=true

MasterDataSourceConfig.java

注:Primary注解代表該數(shù)據(jù)源為主數(shù)據(jù)源

package com.core.dataSource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * oracle數(shù)據(jù)配置
 */
@Configuration
//配置mapper文件目錄,進(jìn)行掃描
@MapperScan(basePackages = "com.wawj.core.mapper.master", sqlSessionTemplateRef = "masterSqlSessionTemplate")
public class MasterDataSourceConfig {

    /**
     * 創(chuàng)建數(shù)據(jù)源
     * @return
     */
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 創(chuàng)建工廠
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //指定mapper.xml的目錄
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/master/**/*.xml"));
        //指定實(shí)體類目錄
        bean.setTypeAliasesPackage("com.wawj.core.entity");
        return bean.getObject();
    }

    /**
     * 創(chuàng)建事務(wù)
     * @param dataSource
     * @return
     */
    @Bean
    @Primary
    public DataSourceTransactionManager masterTransactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 創(chuàng)建模板
     * @param sqlSessionFactory
     * @return
     */
    @Bean
    @Primary
    public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

SlaveDataSourceConfig.java

package com.core.dataSource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * mysql數(shù)據(jù)配置
 */
@Configuration
//配置mapper文件目錄,進(jìn)行掃描
@MapperScan(basePackages = "com.wawj.core.mapper.slave", sqlSessionTemplateRef = "slaveSqlSessionTemplate")
public class SlaveDataSourceConfig {

    /**
     * 創(chuàng)建數(shù)據(jù)源
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 創(chuàng)建工廠
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean
    public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //指定mapper.xml的目錄
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/slave/**/*.xml"));
        //指定實(shí)體類目錄
        bean.setTypeAliasesPackage("com.wawj.core.entity");
        return bean.getObject();
    }

    /**
     * 創(chuàng)建事務(wù)
     * @param dataSource
     * @return
     */
    @Bean
    public DataSourceTransactionManager slaveTransactionManager(@Qualifier("slaveDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 創(chuàng)建模板
     * @param sqlSessionFactory
     * @return
     */
    @Bean
    public SqlSessionTemplate slaveSqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

這種方式初始化的是時(shí)候在druid控制臺(tái)(http://localhost:8080/druid/login.html)中的數(shù)據(jù)源標(biāo)簽是沒(méi)有,要請(qǐng)求過(guò)后才會(huì)顯示當(dāng)前連接的數(shù)據(jù)源

二、使用dynamic-datasource 動(dòng)態(tài)配置(項(xiàng)目啟動(dòng)的時(shí)候創(chuàng)建)

pom.xml

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid-spring-boot-starter</artifactId>
   <version>1.1.10</version>
</dependency>

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

<!-- maven倉(cāng)庫(kù)中沒(méi)有oracle數(shù)據(jù)庫(kù)驅(qū)動(dòng),這里將jar 放到工程下進(jìn)行引入 -->
<dependency>
   <groupId>com.ojdbc</groupId>
   <artifactId>ojdbc</artifactId>
   <version>10.2.0.1</version>
   <scope>system</scope>
   <systemPath>${project.basedir}/src/main/lib/ojdbc14-10.2.0.1.0.jar</systemPath>
</dependency>

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.38</version>
</dependency>

application.properties

#全局默認(rèn)值,可以全局更改
spring.datasource.dynamic.druid.initial-size=5
spring.datasource.dynamic.druid.max-active=5
spring.datasource.dynamic.druid.min-idle=5
spring.datasource.dynamic.druid.pool-prepared-statements=true
#配置執(zhí)行多條sql比如:批量處理
#對(duì)應(yīng)的錯(cuò)誤:sql injection violation, multi-statement not allow
spring.datasource.dynamic.druid.wall.multi-statement-allow=true
#配置執(zhí)行特殊sql比如sql server的創(chuàng)建臨時(shí)表(declare)語(yǔ)句
#對(duì)應(yīng)的錯(cuò)誤:sql injection violation, class com.alibaba.druid.sql.ast.statement.SQLDeclareStatement not allow
spring.datasource.dynamic.druid.wall.none-base-statement-allow=true

#oracle數(shù)據(jù)庫(kù)
spring.datasource.dynamic.datasource.master.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.dynamic.datasource.master.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.dynamic.datasource.master.url=jdbc:oracle:thin:@localhost:1521:test
spring.datasource.dynamic.datasource.master.username=oracle
spring.datasource.dynamic.datasource.master.password=123456

#mysql數(shù)據(jù)庫(kù)
spring.datasource.dynamic.datasource.slave.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.dynamic.datasource.slave.druid.validation-query=SELECT 1
spring.datasource.dynamic.datasource.slave.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8
spring.datasource.dynamic.datasource.slave.username=mysql
spring.datasource.dynamic.datasource.slave.password=123456

#指定master為主數(shù)據(jù)源
spring.datasource.dynamic.primary=master
#排除原生Druid的快速配置類(DruidDataSourceAutoConfigure會(huì)注入一個(gè)DataSourceWrapper,其會(huì)在原生的spring.datasource下找url,username,password等。而我們動(dòng)態(tài)數(shù)據(jù)源的配置路徑是變化的。)
spring.autoconfigure.exclude=com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure

#設(shè)置dynamic登錄名
spring.datasource.druid.stat-view-servlet.login-username=admin
#設(shè)置dynamic密碼
spring.datasource.druid.stat-view-servlet.login-password=admin

#mybatis mapper location
mybatis-plus.mapper-locations=classpath:mapper/**/*.xml
mybatis-plus.type-aliases-package=com.wawj.core.entity

這種方式使用注解(@DS("數(shù)據(jù)源名稱"))切換數(shù)據(jù)源

@DS 可以注解在方法上和類上,同時(shí)存在方法注解優(yōu)先于類上注解。

注解在service實(shí)現(xiàn)或mapper接口方法上,但強(qiáng)烈不建議同時(shí)在service和mapper注解。 (可能會(huì)有問(wèn)題)

注解結(jié)果
沒(méi)有@DS默認(rèn)數(shù)據(jù)源
@DS("dsName")dsName可以為組名也可以為具體某個(gè)庫(kù)的名稱

補(bǔ)充:排除原生的DruidDataSourceAutoConfigure也可以在springboot啟動(dòng)類排除(某些springBoot的版本上面可能無(wú)法排除就在application.properties中配置排除)

@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

或

#application.properties
spring.autoconfigure.exclude=com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure

看完上述內(nèi)容,你們對(duì)springboot 中怎么利用mybatis 配置多數(shù)據(jù)源有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI