springboot--jpa 配置多数据库

article/2025/9/30 4:21:44

使用spring boot jpa 配置多数据源

由于项目整合 以前的功能 但是以前功能存储的数据库是另一个数据库

这两天搜索了一下 遇见了许多坑 在这里记录一下

首先附上我的项目结构
在这里插入图片描述
可能有些乱 忘见谅。

pom.xml(把数据库的依赖引入)

<!--    mariadb    --><dependency><groupId>org.mariadb.jdbc</groupId><artifactId>mariadb-java-client</artifactId></dependency><!--sql server数据库--><dependency><groupId>com.microsoft.sqlserver</groupId><artifactId>mssql-jdbc</artifactId><scope>runtime</scope></dependency>

修改yml配置文件

spring:datasource:#主数据库 primary:  #名字可以自定driver-class-name: org.mariadb.jdbc.Driverjdbc-url: jdbc:mariadb://xxx/xxx?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghaiusername: 123password: 123#从数据库secondary: #名字可以自定driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriverjdbc-url: jdbc:sqlserver://www.xx.com:xx/xx?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghaiusername: 123password: 123jpa:hibernate:#方言primary-dialect: org.hibernate.dialect.MySQL5InnoDBDialectsecondary-dialect: org.hibernate.dialect.SQLServerDialect#ddl-auto: validate#    create 启动时删数据库中的表,然后创建,退出时不删除数据表#    create-drop 启动时删数据库中的表,然后创建,退出时删除数据表 如果表不存在报错#    update 如果启动时表格式不一致则更新表,原有数据保留#    validate 项目启动表结构进行校验 如果不一致则报错show-sql: true

然后需要配置类
DataSourceConfig–配置数据源


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 javax.sql.DataSource;/*** 读取application.yml配置的两个数据源,并将其注入到Spring的IOC容器中*/
@Configuration //SpringBoot启动将该类作为配置类,同配置文件一起加载
public class DataSourceConfig {//将该实体注入到IOC容器中@Bean(name = "primaryDataSource")//指定数据源名称,与Bean中的name属性原理相同,主要是为了确保注入成功@Qualifier("primaryDataSource")//指定主数据源@Primary//将配置文件中的数据源读取进到方法中,进行build@ConfigurationProperties(prefix = "spring.datasource.primary")public DataSource primaryDataSource() {return DataSourceBuilder.create().build();}//将该实体注入到IOC容器中@Bean(name = "secondaryDataSource")//指定数据源名称,与Bean中的name属性原理相同,主要是为了确保注入成功@Qualifier("secondaryDataSource")//将配置文件中的数据源读取进到方法中,进行build@ConfigurationProperties(prefix = "spring.datasource.secondary")public DataSource secondaryDataSource() {return DataSourceBuilder.create().build();}
}

然后是配置主数据库
PrimaryConfig


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;/*** 主数据源*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryPrimary",transactionManagerRef = "transactionManagerPrimary",basePackages = {"com.xx.mysql.dao"})    // 指定该数据源操作的DAO接口包
public class PrimaryConfig {@Autowired@Qualifier("primaryDataSource")private DataSource primaryDataSource;@Value("${spring.jpa.hibernate.primary-dialect}")private String primaryDialect;//获取方言@Primary@Bean(name = "entityManagerPrimary")public EntityManager entityManager(EntityManagerFactoryBuilder builder) {return entityManagerFactoryPrimary(builder).getObject().createEntityManager();}@Primary@Bean(name = "entityManagerFactoryPrimary")public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {return builder.dataSource(primaryDataSource).properties(getVendorProperties()).packages("com.xx.mysql.pojo")         //设置实体类所在位置.persistenceUnit("primaryPersistenceUnit").build();}@Autowiredprivate JpaProperties jpaProperties;@Autowiredprivate HibernateProperties hibernateProperties;private Map getVendorProperties() {Map<String,String> map = new HashMap<>();map.put("hibernate.dialect",primaryDialect);// 设置对应的数据库方言map.put("hibernate.ddl-auto","validate");//项目启动表结构进行校验 如果不一致则报错jpaProperties.setProperties(map);return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());// return jpaProperties.getHibernateProperties(new HibernateSettings());}@Primary@Bean(name = "transactionManagerPrimary")public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());}}

由于我使用的版本是springboot 2.1 在这里jpaProperties 没有了getHibernateProperties方法!!!

然后是从数据库
SecondaryConfig


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;/*** 从数据源*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactorySecondary",transactionManagerRef = "transactionManagerSecondary",basePackages = {"com.xx.sqlServer.dao"}) //设置DAO接口层所在包位置
public class SecondaryConfig {@Autowired@Qualifier("secondaryDataSource")private DataSource secondaryDataSource;@Value("${spring.jpa.hibernate.secondary-dialect}")private String secondaryDialect;//获取方言@Bean(name = "entityManagerSecondary")public EntityManager entityManager(EntityManagerFactoryBuilder builder) {return entityManagerFactorySecondary(builder).getObject().createEntityManager();}@Bean(name = "entityManagerFactorySecondary")public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(EntityManagerFactoryBuilder builder) {return builder.dataSource(secondaryDataSource).properties(getVendorProperties()).packages("com.xx.sqlServer.pojo")        //设置实体类所在包的位置.persistenceUnit("primaryPersistenceUnit").build();}@Autowiredprivate JpaProperties jpaProperties;@Autowiredprivate HibernateProperties hibernateProperties;private Map getVendorProperties() {Map<String,String> map = new HashMap<>();map.put("hibernate.dialect",secondaryDialect);map.put("hibernate.ddl-auto","validate");jpaProperties.setProperties(map);return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());}@Bean(name = "transactionManagerSecondary")PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());}}

这样就配置好了 !!!

引用的时候只需要引入对应的dao层接口 即可使用不同的数据库!


http://chatgpt.dhexx.cn/article/TZHxxtKr.shtml

相关文章

Spring Data Jpa 配置多数据源

文章目录 1.配置数据库连接信息2.编写数据源配置类3.编写数据库配置4.目录结构 1.配置数据库连接信息 spring:datasource:db1: # 1.0 Datasourceurl: jdbc:mysql://127.0.0.1:3306/test1?useSSLfalse&serverTimezoneGMT%2b8&characterEncodingutf8&connectTimeo…

springboot2+JPA 配置多数据源(不同类型数据库)

注意&#xff1a;看此篇文章之前&#xff0c;springbootjpa的配置环境应搭建好&#xff0c;不会搭可以自行百度。本文章主要讲述配置JPA多数据源。 1.数据源配置文件 application.properties # 数据源thirded&#xff08;oracle数据库&#xff09; spring.jpa.thirded.databa…

jpa配置(jpa配置连接池)

JPA的实体状态有哪些呢&#xff1f; 该接口拥有众多执行数据查询的接口方法&#xff1a; Object getSingleResult()&#xff1a;执行SELECT查询语句&#xff0c;并返回一个结果&#xff1b; List getResultList() &#xff1a;执行SELECT查询语句&#xff0c;并返回多个结果&…

SpringBoot系列之数据库初始化-jpa配置方式

上一篇博文介绍如何使用spring.datasource来实现项目启动之后的数据库初始化&#xff0c;本文作为数据库初始化的第二篇&#xff0c;将主要介绍一下&#xff0c;如何使用spring.jpa的配置方式来实现相同的效果 I. 项目搭建 1. 依赖 首先搭建一个标准的SpringBoot项目工程&am…

Jpa环境配置及入门(增删改查)

案例&#xff1a;客户的相关操作&#xff08;增删改查&#xff09; 1.分析&#xff1a; 1.搭建环境&#xff1a; 创建maven工程&#xff0c;导入相关坐标&#xff1b; 配置使用jpa的核心配置文件&#xff1b; 位置&#xff1b;需要配置到类路径下叫做 META-INF的文件夹下 命…

PHP多国语言开发:CodeIgniter 2PHP框架中的多国语言,语言包(i18n)库

PHP多国语言开发&#xff1a;CodeIgniter 2PHP框架中的多国语言&#xff0c;语言包&#xff08;i18n&#xff09;多国语言库 引言 我们在CodeIgniter开发中经常会碰到多国语言网站&#xff0c;这里我们就来介绍一种简单有效的多国语言的操作方法。 做什么 语言在地址中是这…

Win 10 添加多国语言

不同用户对电脑系统的语言需求也不一样&#xff0c;出于工作原因需要使用其它语言&#xff0c;比如外国友人需要使用英语&#xff0c;俄罗斯语言等&#xff0c;此时很多用户都以为要下载对应语言版本的系统&#xff0c;然后重新安装系统&#xff0c;其实Win10是支持多国语言的&…

手工编译Flex SDK 多国语言包

项目需要将目前版本提供给其它地区&#xff1a;台湾、日韩等&#xff0c;面临着项目语言的国际化问题。 语言代号&#xff1a; 大陆&#xff1a;zh_CN 台湾&#xff1a;zh_TW 香港&#xff1a;zh_HK … 例如想支持繁体&#xff0c;没有zh_TW语言包怎么办&#xff1f; fl…

DevExpress去除多国语言包

DevExpress作为windows开发中较为强大的第三方组件&#xff0c;能极大的提高编程效率和界面效果。但也要引用它较多的dll文件&#xff0c;它专门有个查看dll程序集依赖的工具&#xff0c;在VS的工具菜单下&#xff1a; 在VS的工具菜单内有"DevExpress Assembly Deploymen…

关于VS编译DevExpress默认产生几个多余的多国语言包的问题解决

关于VS编译DevExpress默认产生几个多余的多国语言包的问题解决 VS15开始对于非系统的Dll都会默认复制到本地&#xff0c;即bin\debug下面&#xff0c;复制dll到本地好处在于发布的时候不用再去寻找相关dll,对于dev这么庞大的组件来说&#xff0c;更是如此&#xff0c;当然&…

php源码添加多国语言包,为win7系统添加多国语言包的方法

现在使用win7系统的人越来越多了&#xff0c;对于一些需求也是有所增长&#xff0c;很多用户希望能够将自己的操作系统安装成英文&#xff0c;法文&#xff0c;德文等语言&#xff0c;尤其是对经常出去外国出处的用户很有好吃&#xff0c;比如要和外国客户沟通交流时能看的懂自…

laravel框架安装多国语言包

laravel的一些提示信息都是默认英文&#xff0c;想更改为中文需要下载语言包&#xff0c;执行以下命令 composer require caouecs/laravel-lang:~3.0 执行完后将vendor中的caouecs中的src中的zh-CN文件夹放到views的lang文件夹中 然后还要更改配置项&#xff0c;将config里面…

window10c语言下载,[下载备用]Windows 10多国语言包和独立语言包下载

微软在上周发布Windows 10 周年更新版本之前&#xff0c;已经更新了微软支持库中的Windows 10多国语言包。 此次更新的Windows 10 多国语言包已经可以支持到Windows 10 Version 1607版本&#xff0c;也就是Windows 10 周年更新版本。 不过完整的多国语言包含有超过100种语言的独…

Android多国语言包

生成中文名称的APP如下&#xff1a; step1. step2. step3. step4. step5. 以上步骤仅仅是添加values-zh-rCN文件夹&#xff0c;在AS的res中是看不到的&#xff0c;即使同步后。 这是因为里面没有内容&#xff0c;只需要把默认的string.xml copy到刚才的文件夹中&#xff0c;将…

android语言包,安卓系统添加多国语言包

虽然Android 从 2.3 开始已经支持50种以上的语言,但是不是每种语言都有字体可以显示。遇到一个新需求, 有客户要求对 hindi  语言的支持。于是上 网找了一些资料,发现网上介绍的大部分是如何替换默认字体,就 是替换./works//data/fonts /DroidSansFallback.ttf,但是替换完…

invoke和begininvoke的使用

首先说下&#xff0c;invoke和begininvoke的使用有两种情况&#xff1a; 1. control中的invoke、begininvoke。 2. delegrate中的invoke、begininvoke。 这两种情况是不同的&#xff0c;我们这里要讲的是第1种。下面我们在来说下.NET中对invoke和begininvoke的官方定义。 con…

异步编程模式BeginInvoke和EndInvoke方法

转载自&#xff1a;异步编程模式BeginInvoke与EndInvoke方法 为什么要进行异步回调&#xff1f;众所周知&#xff0c;普通方法运行&#xff0c;是单线程的&#xff0c;如果中途有大型操作&#xff08;如&#xff1a;读取大文件&#xff0c;大批量操作数据库&#xff0c;网络传…

C# 异步委托 BeginInvoke EndInvoke

1. 简单主线程中委托: static void Main(string[] args) {//定义一个委托&#xff0c;并初始化Func<int, int, string> delFunc (a, b) > (a b).ToString();//黄色底纹部分换成{ return (a b).ToString(); }更好理解//同步方法调用&#xff08;跟调用一个方法一样…

Invoke and BeginInvoke

本文转自&#xff1a;http://www.cnblogs.com/worldreason/archive/2008/06/09/1216127.html 在Invoke或者BeginInvoke的使用中无一例外地使用了委托Delegate&#xff0c;至于委托的本质请参考我的另一随笔&#xff1a;对.net事件的看法。 一、为什么Control类提供了Invoke和…

C# Thread Delegate MethodInvoker Invoke BeginInvoke 关系

异步调用是CLR为开发者提供的一种重要的编程手段&#xff0c;它也是构建高性能、可伸缩应用程序的关键。在多核CPU越来越普及的今天&#xff0c;异步编程允许使用非常少的线程执行很多操作。我们通常使用异步完成许多计算型、IO型的复杂、耗时操作&#xff0c;去取得我们的应用…