欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot+Mybatis+Durid整合多数据源的三种方式,第一种

程序员文章站 2022-10-03 15:56:55
概述:项目在研发过程会遇到读取多个数据库的情况,这个时候就需要动态切换数据源用于适应系统的需求,下面我介绍三种实现方式(原理就是两种);废话少说,上硬货!!第一步:pom引入依赖: 1.8 org.springframework.boot...

概述:项目在研发过程会遇到读取多个数据库的情况,这个时候就需要动态切换数据源用于适应系统的需求,下面我介绍三种实现方式(原理就是两种);
废话少说,上硬货!!
第一步:pom引入依赖:
<java.version>1.8</java.version>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-tomcat -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <version>2.2.4.RELEASE</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <!--<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>-->
    <!-- runtime 会引发问题,所以使用下面依赖,规定版本 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.15</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <version>9.0.19</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.2.4</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

第二步:yml配置:需要配置连接池另行百度。

server:
  port: 9090
pagehelper:
  helper‐dialect: mysql
spring:
  datasource:
    arraign:
      jdbc-url: jdbc:mysql://------/arraign?characterEncoding=utf-8
      username: yctx
      password: password
      driverClassName: com.mysql.cj.jdbc.Driver
    dzbl:
      jdbc-url: jdbc:mysql://------/dzbl?characterEncoding=utf-8
      username: dzbl
      password: password
      driverClassName: com.mysql.cj.jdbc.Driver
mybatis:
  type-aliases-package: com.alimather.myitem.bean
  mapper-locations: mapper/*.xml

下面进入正题:
第一种实现方式,通过不同包下来读取不同数据源(分包:)
我的文件路径:
SpringBoot+Mybatis+Durid整合多数据源的三种方式,第一种
1.DataSource配置类:
<1.>DataSourceConfigToArraign

package com.alimather.myitem.datasourceconfig;

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;

/**
 * 任务:
 * 描述:
 * 作者:YJG86166
 * 日期:2020/5/20 8:19
 * @author 86166
 */
@Configuration
@MapperScan(basePackages = "com.alimather.myitem.mapper.arraignsource", sqlSessionFactoryRef = "arraignSqlSessionFactory")
public class DataSourceConfigToArraign {
    @Bean(name = "arraignDataSource")
    @Primary
    /** prefix表示参数的前缀*/
    @ConfigurationProperties(prefix = "spring.datasource.arraign")
    public DataSource getDateSourceArraign() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "arraignSqlSessionFactory")
    @Primary
    /** @Qualifier表示查找Spring容器中名字为arraignDataSource的对象*/
    public SqlSessionFactory arraignSqlSessionFactory(@Qualifier("arraignDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
        // 设置mybatis的xml所在位置
        new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/arraignmapper/*.xml"));
        return bean.getObject();
    }
    @Bean("arraignSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate arraignSqlSessionTemplate(
            @Qualifier("arraignSqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
}

<2.>DataSourceConfigToDzbl

package com.alimather.myitem.datasourceconfig;

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;

/**
 * 任务:
 * 描述:
 * 作者:YJG
 * 日期:2020/5/20 8:19
 * @author 86166
 */
@Configuration
@MapperScan(basePackages = "com.alimather.myitem.mapper.dzblsource", sqlSessionFactoryRef = "dzblSqlSessionFactory")
public class DataSourceConfigToDzbl {
    @Bean(name = "dzblDataSource")
    /** prefix表示参数的前缀*/
    @ConfigurationProperties(prefix = "spring.datasource.dzbl")
    public DataSource getDateSourceDzbl() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "dzblSqlSessionFactory")
    /** @Qualifier表示查找Spring容器中名字为dzblDataSource的对象*/
    public SqlSessionFactory dzblSqlSessionFactory(@Qualifier("dzblDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
        // 设置mybatis的xml所在位置
        new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/dzblmapper/*.xml"));
        return bean.getObject();
    }
    @Bean("dzblSqlSessionTemplate")
    public SqlSessionTemplate dzblSqlSessionTemplate(
            @Qualifier("dzblSqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
}

2.开始使用:<service层>

package com.alimather.myitem.service;

import com.alimather.myitem.bean.SysAclModule;
import com.alimather.myitem.mapper.dzblsource.SysAclModuleMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * 任务:
 * 描述:
 * 作者:YJG86166
 * 日期:2020/5/20 9:05
 * @author 86166
 */
@Service
public class SysAclModuleService {

    @Autowired
    private SysAclModuleMapper sysAclModuleMapper;

    public HashMap<String,Object> listSysAclModule(int page,int size){
        HashMap<String,Object> map = new HashMap<>(2);
        PageHelper.startPage(page,size);
        Page<SysAclModule> sysAclModulePage = sysAclModuleMapper.listSysAclModule();
        List<SysAclModule> sysAclModules = sysAclModulePage.getResult();
        long total = sysAclModulePage.getTotal();
        map.put("data",sysAclModules);
        map.put("total",total);
        return map;
    }

}

<mapper层>

package com.alimather.myitem.mapper.arraignsource;

import com.alimather.myitem.bean.SysAcl;
import com.github.pagehelper.Page;
import org.apache.ibatis.annotations.Mapper;

/**
 * @author 86166
 */
@Mapper
public interface SysAclMapper {
    /**获取表信息
     * @return 分页表信息*/
    Page<SysAcl> listSysAcl();
}

最后,相信大家也看懂了,很简单的一种方式,读取不同数据源就要引用不同mapper就好了。
第二种/第三种,请看进入我的博客主页,里面有;其中第三种方式是我系统正在使用的。经过长时间使用没有问题。

本文地址:https://blog.csdn.net/weixin_44253327/article/details/107589395