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.mzph.cn/web/37928.shtml

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

相关文章

计算机相关术语科普之什么叫网关(Gateway)

网关&#xff08;Gateway&#xff09;是一个在计算机网络中起到关键作用的设备或系统&#xff0c;它扮演着网络间连接器或协议转换器的角色。 一、定义与功能 1&#xff09;定义&#xff1a; 网关是在不同网络之间实现互连的复杂设备&#xff0c;仅用于两个高层协议不同的网…

【PYG】Planetoid中边存储的格式,为什么打印前十条边用edge_index[:, :10]

edge_index 是 PyTorch Geometric 中常用的表示图边的张量。它通常是一个形状为 [2, num_edges] 的二维张量&#xff0c;其中 num_edges 表示图中边的数量。每一列表示一条边&#xff0c;包含两个节点的索引。 实际上这是COO存储格式&#xff0c;官方文档里也有写&#xff0c;…

Web 品质标准

Web 品质标准 引言 随着互联网的快速发展,Web应用已经渗透到我们生活的方方面面。为了确保Web应用的质量,提高用户体验,Web品质标准应运而生。这些标准涵盖了多个方面,包括性能、安全性、可访问性、用户体验等。本文将详细介绍这些标准,并探讨它们在实际开发中的应用。 …

上位机图像处理和嵌入式模块部署(mcu 项目1:固件编写)

【 声明&#xff1a;版权所有&#xff0c;欢迎转载&#xff0c;请勿用于商业用途。 联系信箱&#xff1a;feixiaoxing 163.com】 说完了上位机的开发&#xff0c;接下来就是固件的开发。前面我们说过&#xff0c;目前使用的开发板是极海apm32f103的开发板。它自身包含了iap示例…

一些迷你型信息系统

只有一个表&#xff0c;比较简单易用&#xff1b; 1 博物馆信息查询系统 信息录入&#xff0c;浏览&#xff0c;添加&#xff0c;更新&#xff0c;删除&#xff1b; 下载&#xff0c; https://download.csdn.net/download/bcbobo21cn/89505217

中国网络安全审查认证和市场监管大数据中心数据合规官CCRC-DCO

关于CCRC-DCO证书的颁发机构&#xff0c;它是由中国网络安全审查认证与市场监管大数据中心&#xff08;简称CCRC&#xff09;负责。 该中心在2006年得到中央机构编制委员会办公室的批准成立&#xff0c;隶属于国家市场监督管理总局&#xff0c;是其直辖的事业单位。 依据《网络…

计算机的错误计算(十八)

摘要 计算机的错误计算&#xff08;四&#xff09;指出一元二次方程的计算精度问题。本节给出其一种解决方案。 计算机的错误计算&#xff08;四&#xff09;与&#xff08;十七&#xff09;分别指出一元二次方程的求解是具有挑战性的难题&#xff0c;其出错原因是因为相减相消…

YOLOv10(7):YOLOv10训练(以训练VOC数据集为例)

YOLOv10&#xff08;1&#xff09;&#xff1a;初探&#xff0c;训练自己的数据_yolov10 训练-CSDN博客 YOLOv10&#xff08;2&#xff09;&#xff1a;网络结构及其检测模型代码部分阅读_yolov10网络结构图-CSDN博客 YOLOv10&#xff08;4&#xff09;&#xff1a;损失&…

汽车之家论坛评论全面采集实战指南:Python爬虫篇

聚焦汽车之家&#xff0c;解锁评论宝藏 在这个数据为王的时代&#xff0c;每一个角落的信息都可能成为宝贵的洞察来源。汽车之家&#xff0c;作为汽车行业内的权威论坛&#xff0c;其海量的用户评论不仅是消费者购车的重要参考&#xff0c;也是汽车品牌与市场研究者不可忽视的…

【Android面试八股文】在你之前的Android项目中,你是如何进行性能优化的?

在之前的Android项目中,优化和提升性能是一个重要且常见的任务。 以下是一些常用的性能优化方法和策略: 分析和测量: 使用Android Studio中的Profiling工具(如Profiler、Trace等)进行性能分析,识别CPU、内存和网络使用情况。使用第三方工具(如Systrace)来分析系统层面…

iOS 练习项目 Landmarks (四):添加 AutoLayout 约束

iOS 练习项目 Landmarks &#xff08;四&#xff09;&#xff1a;添加 AutoLayout 约束 iOS 练习项目 Landmarks &#xff08;四&#xff09;&#xff1a;添加 AutoLayout 约束新增 topLabel图片视图圆形裁切阴影使用 AutoLayout 为详情页的组件添加约束DetailViewControllerDe…

如何在 Logback 和 Log4j 中获取日志:一个开发者指南

日志记录是软件开发中的关键实践&#xff0c;它帮助我们监控应用程序的行为&#xff0c;定位问题并优化性能。在 Java 生态系统中&#xff0c;Logback 和 Log4j 是两个广泛使用的日志框架&#xff0c;它们都基于 SLF4J API 提供日志服务。本文将指导你如何在这两个框架中获取日…

7-490 将字符串“software“赋给一个字符指针,并从第一个字母开始间隔地输出该串(简单字符串)

编程将字符串"software"赋给一个字符指针 然后从第一个字母开始间隔地输出该串 请用指针法完成。 输入样例: 在这里给出一组输入。例如&#xff1a; 无输入输出样例: 在这里给出相应的输出。例如&#xff1a; sfwr #include <stdio.h> #include <stri…

Linux环境下快速部署Spring Boot应用:高效命令组合实践

概要&#xff1a; 本文旨在介绍一种高效的Linux命令组合&#xff0c;用于简化Spring Boot项目的部署与管理流程。通过结合使用nohup、java -jar、输出重定向以及进程管理命令&#xff0c;我们能够实现Spring Boot应用的快速后台启动及便捷的进程控制&#xff0c;尤其适合于自动…

什么是 JVM( Java 虚拟机),它在 Java 程序执行中扮演什么角色?

JVM&#xff0c;全称Java Virtual Machine&#xff0c;中文译作“Java虚拟机”&#xff0c;它是运行Java程序的软件环境&#xff0c;也是Java语言的核心部分之一。 想象一下&#xff0c;如果你是一位环球旅行家&#xff0c;每到一个新的国家&#xff0c;都需要学习当地的语言才…

【Linux】初识操作系统

一、冯•诺依曼体系结构 在学习操作系统之前&#xff0c;我们先来认识一下冯•诺依曼体系结构&#xff0c;我们常见的计算机&#xff0c;如笔记本。我们不常见的计算机&#xff0c;如服务器&#xff0c;大部分都遵守冯诺依曼体系。 截至目前&#xff0c;我们所认识的计算机&am…

神经网络训练(一):基于残差连接的图片分类网络(ResNet18)

目录 一、简介:二、图片分类网络1.记载训练数据(torch自带的cifa10数据集)2.数据增强3.模型构建4.模型训练三、完整源码及文档一、简介: 基于残差连接的图片分类网络,本网络使用ResNet18作为基础模块,根据cifa10的特点进行改进网络,使用交叉熵损失函数和SGD优化器。本网…

使用pyqt5编写一个七彩时钟

使用pyqt5编写一个七彩时钟 效果代码解析定义 RainbowClockWindow 类初始化用户界面显示时间方法 完整代码 在这篇博客中&#xff0c;我们将使用 PyQt5 创建一个简单的七彩数字时钟。 效果 代码解析 定义 RainbowClockWindow 类 class RainbowClockWindow(QMainWindow):def _…

【TB作品】温湿度监控系统设计,ATMEGA16单片机,Proteus仿真

题2:温湿度监控系统设计 功能要求: 1)开机显示时间(小时、分)、时分可修改; 2)用两个滑动变阻器分别模拟温度传感器(测量范 围0-100度)与湿度传感器(0-100%),通过按键 可以在数码管切换显示当前温度值、湿度值; 3)当温度低于20度时,红灯长亮; 4)当湿度高于70%时,黄灯长亮; 5)当…

安卓实现微信聊天气泡

一搜没一个能用的&#xff0c;我来&#xff1a; 布局文件&#xff1a; <?xml version"1.0" encoding"utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android"http://schemas.android.com/apk/res/android"xml…