避坑版:springboot+JPA如何配多种数据源(postgresql+mysql)

本文主要是介绍避坑版:springboot+JPA如何配多种数据源(postgresql+mysql),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

注意: JPA和mybatis是不同的持久层,各自特点独特,

与mybatis相比,JPA需要考虑对数据源的映射和操作,

通常我们设置在项目启动时,JPA就会根据设置去创建或者更新表,

因此不能像mybayis那样等到调用时再去告诉方法用哪个数据源,

JPA需要一开始就设定好repository和entity所对应的数据源,

在下列文件repository里你可以看到相关设置;

坑,请注意,网上有很多的JPA配多种数据源,但是他们都缺失一点,连方言都没有设置,有的压根不知道这回事,要知道,JPA对不同的数据库以及数据库不同版本有不同的数据方言,

此处一定要手动去设置各自不同的方言,在我的数据源设置那你可以看到手动设置方言,如果你不设置,那除非你把ddl_auto设置为none,可那样的话,项目才开始搭建,你就把JPA的特性干掉了一部分,多尴尬

application.properties数据源配置文件

#pg\u5E93
spring.pg.datasource.show-sql=true
spring.jpa.properties.hibernate.pg-dialect=org.hibernate.dialect.PostgreSQLDialect
spring.pg.datasource.hibernate.ddl-auto=update
spring.pg.datasource.platform=postgres
spring.pg.datasource.jdbc-url=jdbc:postgresql://localhost:7017/ddb
spring.pg.datasource.username=ddb_user
spring.pg.datasource.password=FSCn2qS8
spring.pg.datasource.driver-class-name=org.postgresql.Driver
#mysql
spring.mysql.datasource.show-sql=true
spring.jpa.properties.hibernate.mysql-dialect=org.hibernate.dialect.MySQL8Dialect
spring.mysql.datasource.hibernate.ddl-auto=update
spring.mysql.datasource.jdbc-url=jdbc:mysql://localhost:3306/testData?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8&allowPublicKeyRetrieval=true
spring.mysql.datasource.username=root
spring.mysql.datasource.password=666666
spring.mysql.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
DataSourceConfig.java 数据源实例
package com.hikvision.aries.jc.ihswfld.web.modules.dbconfig;/*** @Author: * @Description:* @Date: 2021/8/28 13:58* @Modified By:* @since v1.0.1*/
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;/*** 数据源的配置*/
@Configuration
public class DataSourceConfig {@Bean(name = "pgDataSource")@Qualifier("pgDataSource")@ConfigurationProperties(prefix = "spring.pg.datasource")@Primarypublic DataSource pgDataSource() {return DataSourceBuilder.create().build();}@Bean(name = "mysqlDataSource")@Qualifier("mysqlDataSource")@ConfigurationProperties(prefix = "spring.mysql.datasource")public DataSource mysqlDataSource() {return DataSourceBuilder.create().build();}}
PgConfig.java   pg数据源的配置
package com.hikvision.aries.jc.ihswfld.web.modules.dbconfig;/*** @Author: * @Description:* @Date: 2021/8/28 13:58* @Modified By:* @since v1.0.1*/
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.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.EntityManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;/*** 数据源一*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryPg",transactionManagerRef = "transactionManagerPg",basePackages = {"xx.xx.xx.repository"}) //设置Repository所在位置public class PgConfig {@Autowired@Qualifier("pgDataSource")private DataSource pgDataSource;//方言@Value("${spring.jpa.properties.hibernate.pg-dialect}")private String pgDialect;//表操作@Value("${spring.pg.datasource.hibernate.ddl-auto}")private String pg_ddl_auto;@Value("${spring.pg.datasource.show-sql}")private String pg_show_sql;@Primary@Bean(name = "entityManagerPg")public EntityManager entityManager(EntityManagerFactoryBuilder builder) {return entityManagerFactoryPg(builder).getObject().createEntityManager();}@Primary@Bean(name = "entityManagerFactoryPg")public LocalContainerEntityManagerFactoryBean entityManagerFactoryPg(EntityManagerFactoryBuilder builder) {LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();em.setDataSource(pgDataSource);em.setPackagesToScan(new String[] { "com.hikvision.aries.jc.ihswfld.web.modules.repository.entity" });HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();em.setJpaVendorAdapter(vendorAdapter);HashMap<String, Object> properties = new HashMap<>();properties.put("hibernate.hbm2ddl.auto",pg_ddl_auto);properties.put("hibernate.dialect",pgDialect);properties.put("hibernate.show_sql",pg_show_sql);em.setJpaPropertyMap(properties);return em;}@Primary@Bean(name = "transactionManagerPg")public PlatformTransactionManager transactionManagerPg(EntityManagerFactoryBuilder builder) {return new JpaTransactionManager(entityManagerFactoryPg(builder).getObject());}
}
MysqlConfig.java 数据源的配置
package com.hikvision.aries.jc.ihswfld.web.modules.dbconfig;/*** @Author: * @Description:* @Date: 2021/8/28 13:59* @Modified By:* @since v1.0.1*/
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.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.EntityManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;/*** 数据源二*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryMysql",transactionManagerRef = "transactionManagerMysql",basePackages = {"xx.xx.xx.mysqlRepository"}) //设置Repository所在位置,两个数据库对应的repository和实体类需要不同的路径
public class MysqlConfig {@Autowired@Qualifier("mysqlDataSource")private DataSource mysqlDataSource;//方言@Value("${spring.jpa.properties.hibernate.mysql-dialect}")private String mysqlDialect;//表操作@Value("${spring.mysql.datasource.hibernate.ddl-auto}")private String mysq_ddl_auto;@Value("${spring.mysql.datasource.show-sql}")private String mysql_show_sql;@Bean(name = "entityManagerMysql")public EntityManager entityManager(EntityManagerFactoryBuilder builder) {return entityManagerFactoryMysql(builder).getObject().createEntityManager();}@Bean(name = "entityManagerFactoryMysql")public LocalContainerEntityManagerFactoryBean entityManagerFactoryMysql(EntityManagerFactoryBuilder builder) {LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();em.setDataSource(mysqlDataSource);em.setPackagesToScan(new String[] { "com.hikvision.aries.jc.ihswfld.web.modules.mysqlRepository.entity" });HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();em.setJpaVendorAdapter(vendorAdapter);HashMap<String, Object> properties = new HashMap<>();properties.put("hibernate.hbm2ddl.auto",mysq_ddl_auto);properties.put("hibernate.dialect",mysqlDialect);properties.put("hibernate.show_sql",mysql_show_sql);em.setJpaPropertyMap(properties);return em;}//用来作为数据库事务回滚的限定词//@Transactional(rollbackFor = OAPMException.class, value = "transactionManagerMysql")//事务管理器@Bean(name = "transactionManagerMysql")PlatformTransactionManager transactionManagerMysql(EntityManagerFactoryBuilder builder) {return new JpaTransactionManager(entityManagerFactoryMysql(builder).getObject());}
}

这篇关于避坑版:springboot+JPA如何配多种数据源(postgresql+mysql)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1126640

相关文章

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

SQL Server修改数据库名及物理数据文件名操作步骤

《SQLServer修改数据库名及物理数据文件名操作步骤》在SQLServer中重命名数据库是一个常见的操作,但需要确保用户具有足够的权限来执行此操作,:本文主要介绍SQLServer修改数据... 目录一、背景介绍二、操作步骤2.1 设置为单用户模式(断开连接)2.2 修改数据库名称2.3 查找逻辑文件名

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

SQL Server数据库死锁处理超详细攻略

《SQLServer数据库死锁处理超详细攻略》SQLServer作为主流数据库管理系统,在高并发场景下可能面临死锁问题,影响系统性能和稳定性,这篇文章主要给大家介绍了关于SQLServer数据库死... 目录一、引言二、查询 Sqlserver 中造成死锁的 SPID三、用内置函数查询执行信息1. sp_w

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

java中long的一些常见用法

《java中long的一些常见用法》在Java中,long是一种基本数据类型,用于表示长整型数值,接下来通过本文给大家介绍java中long的一些常见用法,感兴趣的朋友一起看看吧... 在Java中,long是一种基本数据类型,用于表示长整型数值。它的取值范围比int更大,从-922337203685477