广告
返回顶部
首页 > 资讯 > 后端开发 > Python >springboot + JPA 配置双数据源实战
  • 139
分享到

springboot + JPA 配置双数据源实战

2024-04-02 19:04:59 139人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录SpringBoot + JPA 配置双数据源1、首先配置application.yml文件设置主从数据库2、使用配置类读取application.yml配置的两个数据源3、然后

springboot + JPA 配置双数据源

1、首先配置application.yml文件设置主从数据库


spring:
  servlet:
    multipart:
      max-file-size: 20MB
      max-request-size: 20MB
  profiles:
    active: @activatedProperties@
  thymeleaf:
    mode: LEGACYHTML5
    encoding: UTF-8
    cache: false
  Http:
    encoding:
      charset: UTF-8
      enabled: true
      force: true
  jpa:
    hibernate:
      ddl-auto: none
    properties:
      hibernate:
        dialect: org.hibernate.dialect.Mysql5Dialect
    show-sql: true
    database: mysql
 
  datasource:
    primary:
      jdbc-url: jdbc:mysql://192.168.2.180:3306/ssdt-rfid?serverTimezone=Asia/Shanghai
      username: root
      passWord: root
      driver-class-name: com.mysql.cj.jdbc.Driver
 
    secondary:
      jdbc-url: jdbc:mysql://127.0.0.1:3306/isite?serverTimezone=Asia/Shanghai
      username: root
      password: 654321
      driver-class-name: com.mysql.cj.jdbc.Driver
  • 在datasource中存在primary(主数据源) 和secondary (副数据源)两个配置,
  • dialect: org.hibernate.dialect.MySQL5Dialect配置
  • MySQLDialect是MySQL5.X之前的版本,MySQL5Dialect是MySQL5.X之后的版本

2、使用配置类读取application.yml配置的两个数据源

并将其注入到Spring的ioc容器


package com.springboot.***.***.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 javax.sql.DataSource; 
 

@Configuration
public class DataSourceConfig {  
    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.primary")  //  读取配置文件主数据源参数
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
 
    @Bean(name = "secondaryDataSource")
    @Qualifier("secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")  //  读取配置文件副数据源参数
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    } 
}

注解解释:

  • @Configuration:SpringBoot启动将该类作为配置类,同配置文件一起加载
  • @Bean:将该实体注入到IOC容器中
  • @Qualifier:指定数据源名称,与Bean中的name属性原理相同,主要是为了确保注入成功
  • @Primary:指定主数据源
  • @ConfigurationProperties:将配置文件中的数据源读取进到方法中,进行build

3、然后通过类的方式配置两个数据源

对于主次数据源的DAO层接口以及实体POJO类需放在不同目录下,由以下两个配置类中分别指定路径

(1)主数据源


package com.springboot.****.****.config; 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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 = "entityManagerFactoryPrimary",
        transactionManagerRef = "transactionManagerPrimary",
        basePackages = {"com.springboot.****.****.repository"})    // 指定该数据源操作的DAO接口包与副数据源作区分
public class PrimaryConfig { 
    private String url;
 
    public String getUrl() {
        return url;
    }
 
    public void setUrl(String url) {
        this.url = url;
    }
 
    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource;
 
    @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.springboot.****.****.domain.entity")         //设置实体类所在位置与副数据源区分
                .persistenceUnit("primaryPersistenceUnit")
                .build();
    }
 
    private Map getVendorProperties() {
        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.dialect",
                env.getProperty("hibernate.dialect"));
        properties.put("hibernate.ddl-auto",
                "create");
        properties.put("hibernate.physical_naming_strategy",
                "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
        properties.put("hibernate.implicit_naming_strategy",
                "org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy");
        return properties;
    }
 
    @Autowired
    private Environment env; 
    @Primary
    @Bean(name = "transactionManagerPrimary")
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
    } 
}

(2)次数据源


package com.springboot.****.****.config; 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.springboot.****.****.secRepository"}) //设置DAO接口层所在包位置与主数据源区分
public class SecondaryConfig {
 
    @Autowired
    @Qualifier("secondaryDataSource")
    private DataSource secondaryDataSource;
 
    @Bean(name = "entityManagerSecondary")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactorySecondary(builder).getObject().createEntityManager();
    }
 
    @Bean(name = "entityManagerFactorySeAcondary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(secondaryDataSource)
                .properties(getVendorProperties())
                .packages("com.springboot.****.****.secEntity")      //设置实体类所在包的位置与主数据源区分
                .persistenceUnit("primaryPersistenceUnit")
                .build();
    }
 
    private Map getVendorProperties() {
        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto",
                env.getProperty("hibernate.hbm2ddl.auto"));
        properties.put("hibernate.ddl-auto",
                env.getProperty("update"));
        properties.put("hibernate.dialect",
                env.getProperty("hibernate.dialect"));
        properties.put("hibernate.physical_naming_strategy",
                "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
        properties.put("hibernate.implicit_naming_strategy",
                "org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy");
        return properties;
    }
 
    @Autowired
    private Environment env;
 
    @Bean(name = "transactionManagerSecondary")
    PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
    }
}

这两个类主要配置每个数据源,包括事务管理器、以及实体管理器等配置。

注:必须要指定DAO接口所在的包以及实体类所在的包。每个数据源主要操作它指定的资源(DAO接口CURD、实体类)

4、启动类主函数入口

SpringBoot启动类需关闭注解 --程序启动加载的仓库(@EnableJpaRepositories),因为在数据源配置类中已经开启了


@SpringBootApplication
@EnableAsync //开启异步调用
//@EnableJpaRepositories(basePackages = {""}
public class TouchPmsApplication { 
    public static void main(String[] args) {
        SpringApplication.run(TouchPmsApplication.class, args);
    } 
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: springboot + JPA 配置双数据源实战

本文链接: https://www.lsjlt.com/news/135306.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • springboot + JPA 配置双数据源实战
    目录springboot + JPA 配置双数据源1、首先配置application.yml文件设置主从数据库2、使用配置类读取application.yml配置的两个数据源3、然后...
    99+
    2022-11-12
  • SpringBoot+Jpa项目配置双数据源的实现
    目录引言配置yml文件创建数据源配置类为每个数据库创建配置类引言 今天为大家带来一些非常有用的实战技巧,比如在我们需要对两个数据库进行操作的时候而哦我们通常用的只是单数据库查询,这...
    99+
    2022-11-12
  • SpringBoot+Jpa项目配置双数据源怎么实现
    这篇文章主要介绍“SpringBoot+Jpa项目配置双数据源怎么实现”,在日常操作中,相信很多人在SpringBoot+Jpa项目配置双数据源怎么实现问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Sprin...
    99+
    2023-06-22
  • springboot怎么配置双数据源
    在Spring Boot中配置双数据源,可以使用多个数据源的配置,并为每个数据源创建对应的Bean。以下是配置双数据源的步骤:1. ...
    99+
    2023-10-27
    springboot
  • Springboot整合JPA配置多数据源流程详解
    目录1. Maven2. 基本配置DataSource3. 多数据源配置3.1 JpaConfigOracle3.2 JpaConfigMysql4. Dao层接口1. Maven ...
    99+
    2022-11-21
    Springboot整合JPA配置多数据源 Springboot多数据源
  • Springboot启动不检查JPA的数据源配置方式
    目录Springboot启动不检查JPA的数据源配置1.问题2.方案设置Springboot项目忽略JPA启动解决方案Springboot启动不检查JPA的数据源配置 1.问题 有时...
    99+
    2022-11-12
  • 如何使用SpringBoot 配置Oracle和H2双数据源
    这篇文章给大家分享的是有关如何使用SpringBoot 配置Oracle和H2双数据源的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。配置POM<!-- oracle -->&nbs...
    99+
    2023-06-25
  • 使用springboot+druid双数据源动态配置操作
    目录一、yml配置二、动态切换数据源配置文件1.数据源db12.数据源db2三、多数据源的mapper包最好是分开四、代码中调用总结进行动态切换,需要在类里面配置,顺便解决mybat...
    99+
    2022-11-12
  • springboot多数据源配置
    简介 开发当中经常会遇到需要进行多库多表数据整合的需求,在无法拆分项目的情况下,就需要在一个项目中配置多数据源,实现多库数据的整合。本文是在springboot框架的基础上进行的多数据源配置,可参考,也欢迎指正 1、第一步:applicat...
    99+
    2023-08-24
    spring boot mybatis java database
  • 使用SpringBoot 配置Oracle和H2双数据源及问题
    目录配置POM配置yml配置注入问题在上节使用了H2之后感觉很爽,很轻便,正好有个项目要求简单,最好不适用外部数据库,于是就想着把H2数据库集成进来,这个系统已经存在了一个Oracl...
    99+
    2022-11-12
  • springboot怎么配置双数据库
    在Spring Boot中配置双数据库可以使用多个数据源。可以按照以下步骤进行配置:1. 在application.properti...
    99+
    2023-10-21
    springboot 数据库
  • ssm怎么配置双数据源
    在 AWS Systems Manager (SSM) 中配置双数据源可以通过以下步骤完成:1. 登录 AWS 管理控制台并打开 S...
    99+
    2023-09-21
    ssm
  • springboot数据源如何配置
    Spring Boot提供了多种配置数据源的方式,可以根据具体的需求选择适合的配置方式。1. 使用默认配置:Spring Boot默...
    99+
    2023-10-09
    springboot
  • springboot 中 druid+jpa+MYSQL数据库配置过程
    Druid来自于阿里的一个开源连接池能够提供强大的监控和扩展功能,Spring Boot默认不支持Druid和jpa,需要引入依赖。 1、引入依赖包 <!--druid--...
    99+
    2022-11-12
  • spring boot下mybatis配置双数据源的实例
    目录单一数据源配置多个数据源配置多数据源配置文件多数据源配置类最近项目上遇到需要双数据源的来实现需求,并且需要基于spring boot,mybatis的方式来实现,在此做简单记录。...
    99+
    2022-11-12
  • springboot怎么配置多数据源
    在Spring Boot中配置多个数据源可以通过以下步骤来实现: 在pom.xml文件中添加Spring Boot对多数据源的支...
    99+
    2023-10-23
    springboot
  • springboot中怎么配置数据源
    在Spring Boot中配置数据源有以下几种方式:1. 使用默认的数据源配置:Spring Boot提供了默认的数据源配置,只需要...
    99+
    2023-10-27
    springboot
  • springboot+springJdbc+postgresql 实现多数据源的配置
    背景 最近公司在服务拆迁,接口转移,相同的功能接口到要迁移到对应的服务中,因为时间比较赶,别问为什么没给时间,没人,没资源,但是活还是得干的,为了减少工作量和稳妥的需要分两步走 ...
    99+
    2022-11-12
  • springboot中如何配置多数据源
    这期内容当中小编将会给大家带来有关springboot中如何配置多数据源,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。一、建库建表1.1 创建数据库db1和数据库db21.2 在数据库db1中创建表db1...
    99+
    2023-06-15
  • springboot 中怎么配置DRUID数据源
    本篇文章为大家展示了springboot 中怎么配置DRUID数据源,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。1.修改pom.xml<dependency>  &...
    99+
    2023-06-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作