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);
    } 
}

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

相关文章

  • SpringBoot静态资源路径配置及主页显示

    SpringBoot静态资源路径配置及主页显示

    这篇文章主要介绍了SpringBoot静态资源路径配置及主页显示,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • 详解Java的回调机制

    详解Java的回调机制

    最近学习java,接触到了回调机制(CallBack)。初识时感觉比较混乱,而且在网上搜索到的相关的讲解,本文介绍了Java的回调机制,有兴趣的同学可以了解一下
    2016-10-10
  • 完美解决idea突然间很卡的问题

    完美解决idea突然间很卡的问题

    这篇文章主要介绍了完美解决idea突然间很卡的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • Windows系统中Java调用cmd命令及执行exe程序的方法

    Windows系统中Java调用cmd命令及执行exe程序的方法

    这篇文章主要介绍了Windows系统中Java调用cmd命令及执行exe程序的方法,主要用到了IOException类,需要的朋友可以参考下
    2016-03-03
  • Dubbo框架线程池使用介绍

    Dubbo框架线程池使用介绍

    当我们在使用dubbo的时候,是可以通过调整线程池来达到调优的效果,我们可以在dubbo:protocol 标签中使用用threadpool属性选择自己想要使用的线程池,通过threads属性配置服务线程数,queues属性配置使用的队列
    2022-09-09
  • Maven 生成打包可执行jar包的方法步骤

    Maven 生成打包可执行jar包的方法步骤

    这篇文章主要介绍了Maven 生成打包可执行jar包的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • 使用@RequestBody传递多个不同对象方式

    使用@RequestBody传递多个不同对象方式

    这篇文章主要介绍了使用@RequestBody传递多个不同对象方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • JAVA面试题之Forward与Redirect的区别详解

    JAVA面试题之Forward与Redirect的区别详解

    这篇文章主要给大家介绍了在JAVA面试中可能遇到会遇到的一道题,就是java中Forward与Redirect两者之前的区别,文中介绍的非常详细,对大家具有一定参考学习价值,需要的朋友们下面来一起看看吧。
    2017-05-05
  • NameNode 重启恢复数据的流程详解

    NameNode 重启恢复数据的流程详解

    这篇文章主要为大家介绍了NameNode 重启恢复数据的流程详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-02-02
  • java 中用split分割字符串,最后的空格等不被拆分的方法

    java 中用split分割字符串,最后的空格等不被拆分的方法

    下面小编就为大家带来一篇java 中用split分割字符串,最后的空格等不被拆分的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-02-02

最新评论