springboot + JPA 配置双数据源实战

 更新时间:2021年09月10日 10:55:59   作者:Frankenstein_  
这篇文章主要介绍了springboot + JPA 配置双数据源实战,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

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; 
 
/**
 * @author: SUN
 * @version: 1.0
 * @date: 2019/12/24 13:12
 * @description:
 */
@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;
 
/**
 * @author: SUN
 * @version: 1.0
 * @date: 2019/12/24 13:25
 * @description:
 */
@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;
/**
 * @author: SUN
 * @version: 1.0
 * @date: 2019/12/24 13:59
 * @description:
 */
@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);
    } 
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java中的动态数组和栈Vector Stack使用区别介绍

    Java中的动态数组和栈Vector Stack使用区别介绍

    这篇文章主要为大家介绍了Java中的动态数组和栈Vector Stack使用介绍,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-10-10
  • java编程实现杨辉三角两种输出结果实例代码

    java编程实现杨辉三角两种输出结果实例代码

    这篇文章主要介绍了java编程实现杨辉三角两种输出结果实例代码,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • Spring Aop注解实现

    Spring Aop注解实现

    本文我们通过Spring AOP和Java的自定义注解来实现日志的插入功能,非常不错,具有一定的参考借鉴价值,需要的朋友一起看看吧,希望对你有所帮助
    2021-07-07
  • 详细介绍Java后端API接口开发规范

    详细介绍Java后端API接口开发规范

    在Java后端开发中,API接口的设计与开发至关重要,本文详细介绍了命名规范、接收参数规范、参数检验、接收方式规范、异常类处理、统一返回格式以及幂等性等方面的开发规范,提供了实际代码示例,需要的朋友可以参考下
    2024-10-10
  • JDK完全卸载超详细步骤

    JDK完全卸载超详细步骤

    这篇文章主要给大家介绍了关于JDK完全卸载超详细步骤的相关资料,在安装JDK之前,最好将原来可能安装过的JDK卸载掉,以免影响到新JDK的使用,需要的朋友可以参考下
    2023-08-08
  • Java面试最容易被刷的重难点之锁的使用策略

    Java面试最容易被刷的重难点之锁的使用策略

    锁像synchronized同步块一样,是一种线程同步机制,但比Java中的synchronized同步块更复杂。因为锁(以及其它更高级的线程同步机制)是由synchronized同步块的方式实现的,所以我们还不能完全摆脱synchronized关键字
    2021-10-10
  • SpringBoot详解MySQL如何实现读写分离

    SpringBoot详解MySQL如何实现读写分离

    当响应的瓶颈在数据库的时候,就要考虑数据库的读写分离,当然还可以分库分表,那是单表数据量特别大,当单表数据量不是特别大,但是请求量比较大的时候,就要考虑读写分离了.具体的话,还是要看自己的业务...如果还是很慢,那就要分库分表了...我们这篇就简单讲一下读写分离
    2022-09-09
  • SpringBoot项目调优及垃圾回收器的比较详解

    SpringBoot项目调优及垃圾回收器的比较详解

    这篇文章主要介绍了SpringBoot项目调优及垃圾回收器的比较详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-04-04
  • Java设计模式中的外观模式详解

    Java设计模式中的外观模式详解

    外观模式为多个复杂的子系统,提供了一个一致的界面,使得调用端只和这个接口发生调用,而无须关系这个子系统内部的细节。本文将通过示例详细为大家讲解一下外观模式,需要的可以参考一下
    2023-02-02
  • ShardingSphere jdbc集成多数据源的实现步骤

    ShardingSphere jdbc集成多数据源的实现步骤

    本文主要介绍了ShardingSphere jdbc集成多数据源的实现步骤,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-10-10

最新评论