避坑版: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

相关文章

MySQL 多表连接操作方法(INNER JOIN、LEFT JOIN、RIGHT JOIN、FULL OUTER JOIN)

《MySQL多表连接操作方法(INNERJOIN、LEFTJOIN、RIGHTJOIN、FULLOUTERJOIN)》多表连接是一种将两个或多个表中的数据组合在一起的SQL操作,通过连接,... 目录一、 什么是多表连接?二、 mysql 支持的连接类型三、 多表连接的语法四、实战示例 数据准备五、连接的性

MySQL中的分组和多表连接详解

《MySQL中的分组和多表连接详解》:本文主要介绍MySQL中的分组和多表连接的相关操作,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录mysql中的分组和多表连接一、MySQL的分组(group javascriptby )二、多表连接(表连接会产生大量的数据垃圾)MySQL中的

Java 实用工具类Spring 的 AnnotationUtils详解

《Java实用工具类Spring的AnnotationUtils详解》Spring框架提供了一个强大的注解工具类org.springframework.core.annotation.Annot... 目录前言一、AnnotationUtils 的常用方法二、常见应用场景三、与 JDK 原生注解 API 的

Java controller接口出入参时间序列化转换操作方法(两种)

《Javacontroller接口出入参时间序列化转换操作方法(两种)》:本文主要介绍Javacontroller接口出入参时间序列化转换操作方法,本文给大家列举两种简单方法,感兴趣的朋友一起看... 目录方式一、使用注解方式二、统一配置场景:在controller编写的接口,在前后端交互过程中一般都会涉及

Java中的StringBuilder之如何高效构建字符串

《Java中的StringBuilder之如何高效构建字符串》本文将深入浅出地介绍StringBuilder的使用方法、性能优势以及相关字符串处理技术,结合代码示例帮助读者更好地理解和应用,希望对大家... 目录关键点什么是 StringBuilder?为什么需要 StringBuilder?如何使用 St

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

Java并发编程之如何优雅关闭钩子Shutdown Hook

《Java并发编程之如何优雅关闭钩子ShutdownHook》这篇文章主要为大家详细介绍了Java如何实现优雅关闭钩子ShutdownHook,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 目录关闭钩子简介关闭钩子应用场景数据库连接实战演示使用关闭钩子的注意事项开源框架中的关闭钩子机制1.

Maven中引入 springboot 相关依赖的方式(最新推荐)

《Maven中引入springboot相关依赖的方式(最新推荐)》:本文主要介绍Maven中引入springboot相关依赖的方式(最新推荐),本文给大家介绍的非常详细,对大家的学习或工作具有... 目录Maven中引入 springboot 相关依赖的方式1. 不使用版本管理(不推荐)2、使用版本管理(推

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B