Spring boot配置多数据源代码实例

 更新时间:2020年07月08日 11:54:59   作者:阮帅  
这篇文章主要介绍了Spring boot配置多数据源代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

因项目需要在一个应用里从两个数据库取数,所以需要配置多数据源,网上找了好多方法才启动成功,整理如下。注意两个数据源的repository文件名不能相同,即使在不同的文件夹下,否则系统启动会报错。

配置文件

spring.datasource.primary.url=***
spring.datasource.primary.username=***
spring.datasource.primary.password=***
spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.second.url=***
spring.datasource.second.username=***
spring.datasource.second.password=***
spring.datasource.second.driver-class-name=com.mysql.jdbc.Driver

通用数据源配置

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * @author ruanshuai
 * @date 2020/5/13
 */

@Configuration
public class DataSourceConfig {

  /**
   * 第一个数据连接,默认优先级最高
   * @return
   */
  @Primary
  @Bean(name = "primaryDataSource") //数据源1配置名
  @Qualifier("primaryDataSource") //数据源1配置名
  @ConfigurationProperties(prefix="spring.datasource.primary") //见配置文件
  public DataSource PrimaryDataSource() {
    return DataSourceBuilder.create().type(DruidDataSource.class).build();
  }

  /**
   * 第二个数据源
   * @return
   */
  @Bean(name = "secondDataSource") //数据源2配置名
  @Qualifier("secondDataSource") //数据源2配置名
  @ConfigurationProperties(prefix="spring.datasource.second") //见配置文件
  public DataSource secondaryDataSource() {
    return DataSourceBuilder.create().type(DruidDataSource.class).build();
  }
}

数据源1配置

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.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 ruanshuai
 * @date 2020/5/13
 */

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    entityManagerFactoryRef="entityManagerFactoryPrimary",
    transactionManagerRef="transactionManagerPrimary",
    basePackages= { "***此处为数据源1 repository的存放文件夹***" })
public class PrimaryConfig {


  @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("***实体类所在文件夹,两个数据源的实体类可相同***")
        .persistenceUnit("primaryPersistenceUnit")
        .build();
  }



  private Map<String, String> getVendorProperties() {
    Map<String, String> jpaProperties = new HashMap<>(16);
    jpaProperties.put("hibernate.hbm2ddl.auto", "update");
    jpaProperties.put("hibernate.show_sql", System.getProperty("spring.jpa.show-sql"));
    jpaProperties.put("hibernate.dialect", System.getProperty("spring.jpa.properties.hibernate.dialect"));
    jpaProperties.put("hibernate.current_session_context_class", "org.springframework.orm.hibernate5.SpringSessionContext");
    return jpaProperties;
  }

  @Primary
  @Bean(name = "transactionManagerPrimary")
  public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
    return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
  }
}

数据源2配置

import org.omg.CORBA.Environment;
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.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 ruanshuai
 * @date 2020/5/13
 */

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    //实体管理
    entityManagerFactoryRef="entityManagerFactorySecond",
    //事务管理
    transactionManagerRef="transactionManagerSecond",
    //实体扫描,设置Repository所在位置
    basePackages= { "***此处为数据源1 repository的存放文件夹***" })
public class SecondConfig {

  @Autowired
  @Qualifier("secondDataSource")
  private DataSource secondDataSource;


  @Bean(name = "entityManagerSecond")
  public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
    return entityManagerFactorySecond(builder).getObject().createEntityManager();
  }

  @Bean(name = "entityManagerFactorySecond")
  public LocalContainerEntityManagerFactoryBean entityManagerFactorySecond (EntityManagerFactoryBuilder builder) {
    return builder
        .dataSource(secondDataSource)
        .properties(getVendorProperties())
        .packages("***实体类所在文件夹,两个数据源的实体类可相同***")
        .persistenceUnit("secondPersistenceUnit")
        .build();
  }

  private Map<String, String> getVendorProperties() {
    Map<String, String> jpaProperties = new HashMap<>(16);
    jpaProperties.put("hibernate.hbm2ddl.auto", "update");
    jpaProperties.put("hibernate.show_sql", System.getProperty("spring.jpa.show-sql"));
    jpaProperties.put("hibernate.dialect", System.getProperty("spring.jpa.properties.hibernate.dialect"));
    jpaProperties.put("hibernate.current_session_context_class", "org.springframework.orm.hibernate5.SpringSessionContext");
    return jpaProperties;
  }

  @Bean(name = "transactionManagerSecond")
  PlatformTransactionManager transactionManagerSecond(EntityManagerFactoryBuilder builder) {
    return new JpaTransactionManager(entityManagerFactorySecond(builder).getObject());
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • java使用DOM对XML文档进行增删改查操作实例代码

    java使用DOM对XML文档进行增删改查操作实例代码

    这篇文章主要介绍了java使用DOM对XML文档进行增删改查操作实例代码,实例涉及对xml文档的增删改查,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下
    2018-02-02
  • 解决java后台登录前后cookie不一致问题

    解决java后台登录前后cookie不一致问题

    本文主要介绍了java后台登录前后cookie不一致的解决方案,具有很好的参考价值,需要的朋友一起来看下吧
    2016-12-12
  • Java的Spring框架的三种连接池的基本用法示例

    Java的Spring框架的三种连接池的基本用法示例

    这篇文章主要介绍了Java的Spring框架的三种连接池的基本用法示例,Spring框架是Java下注明的SSH三大web开发框架之一,需要的朋友可以参考下
    2015-11-11
  • Java反转字符串和相关字符编码的问题解决

    Java反转字符串和相关字符编码的问题解决

    反转字符串一直被当作是简单问题,大家的思想主要就是利用遍历,首尾交换字符实现字符串的反转。例如下面的代码,就可以简单实现反转。
    2013-05-05
  • SpringCloud项目中Feign组件添加请求头所遇到的坑及解决

    SpringCloud项目中Feign组件添加请求头所遇到的坑及解决

    这篇文章主要介绍了SpringCloud项目中Feign组件添加请求头所遇到的坑及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-04-04
  • Spring Boot ActiveMQ如何设置访问密码

    Spring Boot ActiveMQ如何设置访问密码

    这篇文章主要介绍了Spring Boot ActiveMQ如何设置访问密码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-07-07
  • 深入理解Java显式锁的相关知识

    深入理解Java显式锁的相关知识

    今天带大家学习的是关于Java的相关知识,文章围绕着Java显式锁展开,文中有非常详细的介绍及代码示例,需要的朋友可以参考下
    2021-06-06
  • 三道java新手入门面试题,通往自由的道路--多线程

    三道java新手入门面试题,通往自由的道路--多线程

    这篇文章主要为大家分享了最有价值的3道多线程面试题,涵盖内容全面,包括数据结构和算法相关的题目、经典面试编程题等,对hashCode方法的设计、垃圾收集的堆和代进行剖析,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • 使用jenkins部署springboot项目的方法步骤

    使用jenkins部署springboot项目的方法步骤

    这篇文章主要介绍了使用jenkins部署springboot项目的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-04-04
  • spring中@ComponentScan自动扫描并指定扫描规则

    spring中@ComponentScan自动扫描并指定扫描规则

    本文主要介绍了spring中@ComponentScan自动扫描并指定扫描规则,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04

最新评论