SpringBoot+mybatis+pgsql多个数据源配置

news2024/9/21 21:53:13

一、配置文件

jdk环境:1.8 配置了双数据源springboot+druid+pgsql,application.properties配置修改如下:

#当前入库主数据库
spring.primary.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.primary.datasource.driver-class-name=org.postgresql.Driver
spring.primary.datasource.url=jdbc:postgresql://localhost:5432/testdb
spring.primary.datasource.username=postgres
spring.primary.datasource.password=postgres
#
#从数据库
spring.secondary.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.secondary.datasource.driver-class-name=org.postgresql.Driver
spring.secondary.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.secondary.datasource.username=postgres
spring.secondary.datasource.password=postgres

spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20

二、Java代码配置新增

主数据库注入

/**
 * @Author yang
 * @Date 2023/2/20 11:10
 * @Version 1.0
 */
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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;

@Configuration
@MapperScan(basePackages = MasterDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfig {
    // 精确到master目录,以便跟其他数据源隔离
    static final String PACKAGE = "com.xx.dao.master";
    static final String MAPPER_LOCATION = "classpath*:com/xx/mapper/master/*.xml";

    @Value("${spring.primary.datasource.url}")
    private String url;

    @Value("${spring.primary.datasource.username}")
    private String user;

    @Value("${spring.primary.datasource.password}")
    private String password;

    @Value("${spring.primary.datasource.driver-class-name}")
    private String driverClass;

    private SqlSessionFactory mSessionFactory;


    @Bean(name = "masterDataSource")
    @Primary
    public DataSource masterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "masterTransactionManager")
    @Primary
    public DataSourceTransactionManager masterTransactionManager() {
        return new DataSourceTransactionManager(masterDataSource());
    }

    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(masterDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(MasterDataSourceConfig.MAPPER_LOCATION));
        //开启驼峰
        sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        this.mSessionFactory = sessionFactory.getObject();
        return sessionFactory.getObject();
    }

    /**
     * 获取主库 SessionFactory
     * @return
     */
    public SqlSessionFactory getMSessionFactory(){
        return mSessionFactory;
    }

}

从数据库Java代码:

/**
 * @Author yang
 * @Date 2023/2/20 11:52
 * @Version 1.0
 */
@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = SecondDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondDataSourceConfig {
    //精确到第二个数据库目录,以便跟其他数据源隔离
    static final String PACKAGE = "com.xx.dao.second";
    static final String MAPPER_LOCATION = "classpath*:com/xx/mapper/second/*.xml";

    @Value("${spring.secondary.datasource.url}")
    private String url;

    @Value("${spring.secondary.datasource.username}")
    private String user;

    @Value("${spring.secondary.datasource.password}")
    private String password;

    @Value("${spring.secondary.datasource.driver-class-name}")
    private String driverClass;

    @Bean(name = "secondDataSource")
    public DataSource clusterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "secondTransactionManager")
    public DataSourceTransactionManager clusterTransactionManager() {
        return new DataSourceTransactionManager(clusterDataSource());
    }

    @Bean(name = "secondSqlSessionFactory")
    public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("secondDataSource") DataSource clusterDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(clusterDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(SecondDataSourceConfig.MAPPER_LOCATION));
        //开启驼峰
        sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return sessionFactory.getObject();
    }
}

三、mapper接口、mybatis/xml文件配置

     这里就就不一一贴代码了,主要是接口对应mybatis xml配置文件。项目文件接口如下:

创建成以上目录就可以了,分别是dao接口、Java数据源配置、mybatis映射文件。

四、怎么使用

      通过以上配置文件和代码已经对两个数据源进行分割,直接正常使用访问代码即可,比如dao里面创建了testClass的操作

void insert(Test test);
void delete();

Controller层我们通过@Autowired注解 使用就可以了。

这里需要注意修改:

@MapperScan里面的basePackages

MAPPER_LOCATION变量的配置,这里主要是不同的数据源配置扫描不同的mybatis配置文件

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/931982.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

太阳能光伏产业链特征

从太阳能光伏产业链上来看,上游产业是原材料的生产环节,主要是对硅矿石和高纯度硅料的开采、提炼和生产,如冶金硅提纯、多晶硅提纯、单晶/多晶硅片加工与切割等环节。此外还包括太阳能电背板、电池用玻璃等系统配件的制造。 中游产业是技术核…

Day979.OAuth2.0可能存在的安全问题 -OAuth 2.0

OAuth2.0可能存在的安全问题 Hi,我是阿昌,今天学习记录的是关于OAuth2.0可能存在的安全问题的内容。 “OAuth 2.0 不是一种安全协议吗,不是保护 Web API 的吗?为啥 OAuth 2.0 自己还有安全的问题了呢?” 首先&#x…

积跬步至千里 || 数学基础、算法与编程

数学基础、算法与编程 1. BAP 技能 BAP 技能是指基础(Basic)、算法(Algorithm)和编程(Programm)三种基本技能的深度融合。理工科以数学、算法与编程为根基,这三个相辅相成又各有区别。 (1)数学以线性代数为主要研究工具和部分微积分技术为手…

Spring boot 集成单元测试

1.引入依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency> 2. 3.编写测试类 package com.enterprise;import com.enterpr…

网络安全02-C段扫描、开放端口

查询网站IP https://seo.chinaz.com/hetianlab.com 扫描指定IP&#xff1a;例&#xff1a;nmap -A -T4 ww.hetianlab.com -oX out.html 扫描指定段&#xff1a;例&#xff1a;nmap -O -Pn -A 192.168.113.1-200 扫描整个C段&#xff1a;例&#xff1a;nmap -O -Pn -A 192.168.…

ChatGPT在医疗系统的应用探索动态

注意&#xff1a;本信息仅供参考&#xff0c;发布该内容旨在传递更多信息的目的&#xff0c;并不意味着赞同其观点或证实其说法。 生成式人工智能&#xff0c;如OpenAI开发的ChatGPT&#xff0c;被认为是可以颠覆医疗行业的工具。尽管该技术刚刚起步&#xff0c;但已有许多医…

python 面试题--2(15题)

目录 1.解释Python中的 GIL&#xff08;全局解释器锁&#xff09;是什么&#xff0c;它对多线程编程有什么影响&#xff1f; 2.Python中的装饰器是什么&#xff1f;如何使用装饰器&#xff1f; 3.解释Python中的迭代器和生成器的区别。 4.什么是Python中的列表解析&#xf…

redis报错WRONGTYPE Operation against a key holding the wrong kind of value

在redis中我们一般存储string、list、hash类型的值&#xff0c;对应的方法分别为 db.StringGet(“key”)、db.ListRange、db.HashGetAll 如果取list类型值时使用了string的方法就会报WRONGTYPE Operation against a key holding the wrong kind of value错误。 redis-cli命令窗…

网络安全之红蓝对抗实战

前言 背景介绍&#xff1a;目标是拿到企业www.xxx.com的《上市商业计划书.docx》&#xff0c;通过 OPENVPN 访问。特别提出的得分规则修改&#xff0c;权限的得分必须有 WEBSHELL/交互式 SHELL&#xff0c;只有一个漏洞回显不给分&#xff0c;更加偏向考察**漏洞利用**而非漏洞…

简单shell脚本的编写

shell脚本就是将命令写入文本中&#xff0c;文本可以被执行。 脚本&#xff1a;本质是一个文件&#xff0c;文件里面存放的是 特定格式的指令&#xff0c;系统可以使用脚本解析器 翻译或解析 指令 并执行&#xff08;它不需要编译&#xff09; shell 既是应用程序&#xff0c…

小研究 - Java虚拟机垃圾收集器的性能分析与调节

垃圾收集器是&#xff2a;&#xff41;&#xff56;&#xff41;虚拟机&#xff08;&#xff2a;&#xff36;&#xff2d;&#xff09;的核心组成部分之一&#xff0c;对&#xff2a;&#xff41;&#xff56;&#xff41;虚拟机的性能有非常重要的影响。本文将介绍&#xff2…

加油站ai视觉分析检测预警

加油站ai视觉分析预警系统通过yolov8图像识别和行为分析&#xff0c;加油站ai视觉分析预警算法识别出打电话抽烟、烟火行为、静电释放时间是否合规、灭火器摆放以及人员工服等不符合规定的行为&#xff0c;并发出预警信号以提醒相关人员。YOLOv8 的推理过程和 YOLOv5 几乎一样&…

什么是异步编程?什么是回调地狱(callback hell)以及如何避免它?

聚沙成塔每天进步一点点 ⭐ 专栏简介⭐ 异步编程⭐ 回调地狱&#xff08;Callback Hell&#xff09;⭐ 如何避免回调地狱1. 使用Promise2. 使用async/await3. 模块化和分离 ⭐ 写在最后 ⭐ 专栏简介 前端入门之旅&#xff1a;探索Web开发的奇妙世界 记得点击上方或者右侧链接订…

Office软件安装包分享(附安装教程)

目录 一、软件简介 二、软件下载 一、软件简介 Office是微软公司开发的一套办公软件套装&#xff0c;包括多个应用程序&#xff0c;如Word、Excel、PowerPoint等&#xff0c;是全球使用最广泛的办公软件之一。以下是Office软件的详细介绍。 1、Office的历史和演变 Office最…

基于和声算法优化的BP神经网络(预测应用) - 附代码

基于和声算法优化的BP神经网络&#xff08;预测应用&#xff09; - 附代码 文章目录 基于和声算法优化的BP神经网络&#xff08;预测应用&#xff09; - 附代码1.数据介绍2.和声优化BP神经网络2.1 BP神经网络参数设置2.2 和声算法应用 4.测试结果&#xff1a;5.Matlab代码 摘要…

go学习-指针 标识符

指针&#xff0c;以及标识符 1.指针 &#xff08;1&#xff09;.基本介绍 1&#xff09;基本数据类型&#xff0c;变量存的值&#xff0c;也叫值类型 2&#xff09;获取变量的地址用&&#xff0c;比如 var num int ,获取num的地址&#xff1a;&num 3)指针类型&…

Java-Lambda表达式

引入 Lambda表达式是在JAVA 8 中引入的&#xff0c;初衷是进一步简化匿名类的语法&#xff08;匿名类还需要在类中实现函数&#xff09;&#xff0c;并使JAVA走向函数式编程。 语法 (parameters) -> expression 或 (parameters) -> { statements; } 可选类型声明。…

手把手教你安装jdk8

前提 我们口中说的Java8、JDK8、JDK1.8都是一个东西 下载 官方下载链接&#xff1a;&#xff08;非翻墙可访问&#xff09; https://www.oracle.com/java/technologies/javase/jdk18-archive-downloads.html 选择如图链接下载&#xff1a;&#xff08;win11,其他系统版本选择…

【C++】C/C++内存管理-new、delete

文章目录 一、C/C内存分布二、C/C中动态内存管理方式2.1 C语言中动态内存管理方式2.2 C内存管理方式 三、operator new和operator delete函数3.1 operator new和operator delete函数3.2 operator new与operator delete的类专属重载&#xff08;了解&#xff09; 四、new和delet…

elementui table 在浏览器分辨率变化的时候界面异常

异常点&#xff1a; 界面显示不完整&#xff0c;表格卡顿&#xff0c;界面已经刷新完成&#xff0c;但是表格的宽度还在一点一点变化&#xff0c;甚至有无线延伸的情况 思路&#xff1a; 1. 使用doLayout 这里官方文档有说明&#xff0c; 所以我的想法是&#xff0c;监听浏览…