Spring Data与多数据源配置

Spring Data与多数据源配置

大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天我们来探讨如何在Spring Data中配置和使用多个数据源。

在现代应用程序中,处理多个数据源变得越来越常见。可能因为不同的数据存储需求,例如读写分离、跨系统数据访问,或者集成多个数据库系统。本文将详细讲解如何在Spring Boot中使用Spring Data配置多个数据源,并提供具体的Java代码示例。

一、项目依赖

首先,我们需要在pom.xml中添加Spring Boot、Spring Data JPA以及数据库驱动的依赖。

<dependencies><!-- Spring Boot Starter Data JPA --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><!-- H2 Database --><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId></dependency><!-- MySQL Database --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>
</dependencies>

二、配置多数据源

我们将配置两个数据源:一个用于H2数据库,另一个用于MySQL数据库。

1. 配置文件

application.yml中配置数据源信息。

spring:datasource:h2:url: jdbc:h2:mem:testdbdriver-class-name: org.h2.Driverusername: sapassword: passwordmysql:url: jdbc:mysql://localhost:3306/testdbdriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: passwordjpa:hibernate:ddl-auto: updateshow-sql: trueproperties:hibernate:dialect: org.hibernate.dialect.H2Dialectformat_sql: true

2. 数据源配置类

我们需要为每个数据源创建单独的配置类。

package cn.juwatech.config;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.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;@Configuration
@EnableTransactionManagement
public class DataSourceConfig {@Primary@Bean(name = "h2DataSource")@ConfigurationProperties(prefix = "spring.datasource.h2")public DataSource h2DataSource() {return DataSourceBuilder.create().build();}@Bean(name = "mysqlDataSource")@ConfigurationProperties(prefix = "spring.datasource.mysql")public DataSource mysqlDataSource() {return DataSourceBuilder.create().build();}@Primary@Bean(name = "h2EntityManagerFactory")public LocalContainerEntityManagerFactoryBean h2EntityManagerFactory(@Qualifier("h2DataSource") DataSource dataSource) {LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();em.setDataSource(dataSource);em.setPackagesToScan("cn.juwatech.model.h2");em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());em.setPersistenceUnitName("h2PU");return em;}@Bean(name = "mysqlEntityManagerFactory")public LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactory(@Qualifier("mysqlDataSource") DataSource dataSource) {LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();em.setDataSource(dataSource);em.setPackagesToScan("cn.juwatech.model.mysql");em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());em.setPersistenceUnitName("mysqlPU");return em;}@Primary@Bean(name = "h2TransactionManager")public PlatformTransactionManager h2TransactionManager(@Qualifier("h2EntityManagerFactory") EntityManagerFactory entityManagerFactory) {return new JpaTransactionManager(entityManagerFactory);}@Bean(name = "mysqlTransactionManager")public PlatformTransactionManager mysqlTransactionManager(@Qualifier("mysqlEntityManagerFactory") EntityManagerFactory entityManagerFactory) {return new JpaTransactionManager(entityManagerFactory);}
}

3. 启用JPA仓库

为每个数据源分别配置JPA仓库。

package cn.juwatech.config;import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;@Configuration
@EnableJpaRepositories(basePackages = "cn.juwatech.repository.h2",entityManagerFactoryRef = "h2EntityManagerFactory",transactionManagerRef = "h2TransactionManager"
)
@EntityScan(basePackages = "cn.juwatech.model.h2")
public class H2DataSourceConfig {
}@Configuration
@EnableJpaRepositories(basePackages = "cn.juwatech.repository.mysql",entityManagerFactoryRef = "mysqlEntityManagerFactory",transactionManagerRef = "mysqlTransactionManager"
)
@EntityScan(basePackages = "cn.juwatech.model.mysql")
public class MysqlDataSourceConfig {
}

三、定义实体类

在不同的包中定义不同数据源的实体类。

package cn.juwatech.model.h2;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;@Entity
public class H2Entity {@Id@GeneratedValue(strategy = GenerationType.AUTO)private Long id;private String name;// getters and setters
}
package cn.juwatech.model.mysql;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;@Entity
public class MysqlEntity {@Id@GeneratedValue(strategy = GenerationType.AUTO)private Long id;private String name;// getters and setters
}

四、定义仓库接口

为每个数据源定义对应的仓库接口。

package cn.juwatech.repository.h2;import cn.juwatech.model.h2.H2Entity;
import org.springframework.data.jpa.repository.JpaRepository;public interface H2EntityRepository extends JpaRepository<H2Entity, Long> {
}
package cn.juwatech.repository.mysql;import cn.juwatech.model.mysql.MysqlEntity;
import org.springframework.data.jpa.repository.JpaRepository;public interface MysqlEntityRepository extends JpaRepository<MysqlEntity, Long> {
}

五、测试多数据源配置

最后,我们编写一个测试类,验证多数据源配置是否成功。

package cn.juwatech;import cn.juwatech.model.h2.H2Entity;
import cn.juwatech.model.mysql.MysqlEntity;
import cn.juwatech.repository.h2.H2EntityRepository;
import cn.juwatech.repository.mysql.MysqlEntityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class MultiDataSourceApplication implements CommandLineRunner {@Autowiredprivate H2EntityRepository h2EntityRepository;@Autowiredprivate MysqlEntityRepository mysqlEntityRepository;public static void main(String[] args) {SpringApplication.run(MultiDataSourceApplication.class, args);}@Overridepublic void run(String... args) throws Exception {H2Entity h2Entity = new H2Entity();h2Entity.setName("H2 Entity");h2EntityRepository.save(h2Entity);MysqlEntity mysqlEntity = new MysqlEntity();mysqlEntity.setName("MySQL Entity");mysqlEntityRepository.save(mysqlEntity);System.out.println("H2 Entities: " + h2EntityRepository.findAll());System.out.println("MySQL Entities: " + mysqlEntityRepository.findAll());}
}

总结

通过本文的介绍,我们展示了如何在Spring Data中配置和使用多个数据源。我们首先配置了数据源,然后为每个数据源创建了单独的配置类和JPA仓库,最后验证了多数据源配置的正确性。这个示例展示了Spring Boot在处理多数据源时的灵活性和强大功能,希望对大家有所帮助。

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

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何找BMS算法、BMS软件的实习

之前一直忙&#xff0c;好久没有更新了&#xff0c;今天就来写一篇文章来介绍如何找BMS方向的实习&#xff0c;以及需要具备哪些条件&#xff0c;我的实习经历都是在读研阶段找的&#xff0c;读研期间两段的实习经历再加上最高影响因子9.4分的论文&#xff0c;我的秋招可以说是…

[22] Opencv_CUDA应用之 使用背景相减法进行对象跟踪

Opencv_CUDA应用之 使用背景相减法进行对象跟踪 背景相减法是在一系列视频帧中将前景对象从背景中分离出来的过程&#xff0c;它广泛应用于对象检测和跟踪应用中去除背景 背景相减法分四步进行&#xff1a;图像预处理 -> 背景建模 -> 检测前景 -> 数据验证 预处理去除…

《昇思25天学习打卡营第9天|onereal》

继续学习昨天的 基于MindNLPMusicGen生成自己的个性化音乐 生成音乐 MusicGen支持两种生成模式&#xff1a;贪心&#xff08;greedy&#xff09;和采样&#xff08;sampling&#xff09;。在实际执行过程中&#xff0c;采样模式得到的结果要显著优于贪心模式。因此我们默认启…

DP:子序列问题

文章目录 什么是子序列子序列的特点举例说明常见问题 关于子序列问题的几个例题1.最长递增子序列2.摆动序列3.最长递增子序列的个数4.最长数对链5.最长定差子序列 总结 什么是子序列 在计算机科学和数学中&#xff0c;子序列&#xff08;Subsequence&#xff09;是指从一个序列…

【JavaEE精炼宝库】多线程进阶(2)synchronized原理、JUC类——深度理解多线程编程

一、synchronized 原理 1.1 基本特点&#xff1a; 结合上面的锁策略&#xff0c;我们就可以总结出&#xff0c;synchronized 具有以下特性(只考虑 JDK 1.8)&#xff1a; 开始时是乐观锁&#xff0c;如果锁冲突频繁&#xff0c;就转换为悲观锁。 开始是轻量级锁实现&#xff…

维护Nginx千字经验总结

Hello , 我是恒 。 维护putty和nginx两个项目好久了&#xff0c;用面向底层的思路去接触 在nginx社区的收获不少&#xff0c;在这里谈谈我的感悟 Nginx的夺冠不是偶然 高速:一方面&#xff0c;在正常情况下&#xff0c;单次请求会得到更快的响应&#xff1b;另一方面&#xff0…

Linux:网络基础1

文章目录 前言1. 协议1.1 为什么要有协议&#xff1f;1.2 什么是协议&#xff1f; 2. 网络2.1 网络通信的问题2.2 网络的解决方案——网络的层状结构2.3 网络和系统的关系2.4 网络传输基本流程2.5 简单理解IP地址2.6 跨网络传输 总结 前言 在早期的计算机发展中&#xff0c;一开…

免费翻译API及使用指南——百度、腾讯

目录 一、百度翻译API 二、腾讯翻译API 一、百度翻译API 百度翻译API接口免费翻译额度&#xff1a;标准版&#xff08;5万字符免费/每月&#xff09;、高级版&#xff08;100万字符免费/每月-需个人认证&#xff0c;基本都能通过&#xff09;、尊享版&#xff08;200万字符免…

Linux驱动开发实战宝典:设备模型、模块编程、I2C/SPI/USB外设精讲

摘要: 本文将带你走进 Linux 驱动开发的世界,从设备驱动模型、内核模块开发基础开始,逐步深入 I2C、SPI、USB 等常用外设的驱动编写,结合实际案例,助你掌握 Linux 驱动开发技能。 关键词: Linux 驱动,设备驱动模型,内核模块,I2C,SPI,USB 一、Linux 设备驱动模型 Li…

cesium 聚合

cesium 聚合(下面附有源码) 示例代码 <html lang="en"><head><!-- Use correct character set. -->

python系列30:各种爬虫技术总结

1. 使用requests获取网页内容 以巴鲁夫产品为例&#xff0c;可以用get请求获取内容&#xff1a; https://www.balluff.com.cn/zh-cn/products/BES02YF 对应的网页为&#xff1a; 使用简单方法进行解析即可 import requests r BES02YF res requests.get("https://www.…

JSON JOLT常用示例整理

JSON JOLT常用示例整理 1、什么是jolt Jolt是用Java编写的JSON到JSON转换库&#xff0c;其中指示如何转换的"specification"本身就是一个JSON文档。以下文档中&#xff0c;我统一以 Spec 代替如何转换的"specification"json文档。以LHS(left hand side)代…

云计算基础技术

网络类技术 网络的作用 网络是设备间、虚拟机之间通信的桥梁。因此&#xff0c;在ICT基础设施中&#xff0c;网络是必不可少的。 传统网络的基本概念 广播和单播&#xff1a;两个设备通信就好像是人们之间的对话一样。如果一个人对另外一个人说话&#xff0c;那么用网络技术的…

从零开始搭建spring boot多模块项目

一、搭建父级模块 1、打开idea,选择file–new–project 2、选择Spring Initializr,选择相关java版本,点击“Next” 3、填写父级模块信息 选择/填写group、artifact、type、language、packaging(后面需要修改)、java version(后面需要修改成和第2步中版本一致)。点击“…

容器内存

一、容器内存概述 容器本质上还是一个进程&#xff0c;是一个被隔离和限制的进程。因此容器内存和进程内存在表现形式上其实是一样的&#xff0c;这块主要涉及三部分内容&#xff1a;RSS&#xff0c;page cache和swap这三部分&#xff0c;容器基于memory Cgroup对内存进行限制…

HSRP热备份路由协议(VRRP虚拟路由冗余协议)配置以及实现负载均衡

1、相关原理 在网络中&#xff0c;如果一台作为默认网关的三层交换机或者路由器损坏&#xff0c;所有使用该网关为下一跳的主机通信必然中断&#xff0c;即使配置多个默认网关&#xff0c;在不重启终端的情况下&#xff0c;也不能彻底换到新网关。Cisco提出了HSRP热备份路由协…

Paragon NTFS与Tuxera NTFS有何区别 Mac NTFS 磁盘读写工具选哪个好

macOS系统虽然以稳定、安全系数高等优点著称&#xff0c;但因其封闭性&#xff0c;不能对NTFS格式磁盘写入数据常被人们诟病。优质的解决方案是使用磁盘管理软件Paragon NTFS for Mac&#xff08;点击获取激活码&#xff09;和Tuxera NTFS&#xff08;点击获取激活码&#xff0…

消防认证-防火卷帘

一、消防认证 消防认证是指消防产品符合国家相关技术要求和标准&#xff0c;且通过了国家认证认可监督管理委员会审批&#xff0c;获得消防认证资质的认证机构颁发的证书&#xff0c;消防产品具有完好的防火功能&#xff0c;是住房和城乡建设领域验收的重要指标。 二、认证依据…

springboot学习,如何用redission实现分布式锁

目录 一、springboot框架介绍二、redission是什么三、什么是分布式锁四、如何用redission实现分布式锁 一、springboot框架介绍 Spring Boot是一个开源的Java框架&#xff0c;由Pivotal团队&#xff08;现为VMware的一部分&#xff09;于2013年推出。它旨在简化Spring应用程序…

C# 警告 warning MSB3884: 无法找到规则集文件“MinimumRecommendedRules.ruleset”

警告 warning MSB3884: 无法找到规则集文件“MinimumRecommendedRules.ruleset” C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Current\Bin\amd64\Microsoft.CSharp.CurrentVersion.targets(129,9): warning MSB3884: 无法找到规则集文件“MinimumRe…