SpringBoot项目中的多数据源支持的方法

1.概述

项目中经常会遇到一个应用需要访问多个数据源的情况,本文介绍在SpringBoot项目中利用SpringDataJpa技术如何支持多个数据库的数据源。

具体的代码参照该 示例项目

2.建立实体类(Entity)

首先,我们创建两个简单的实体类,分别属于两个不同的数据源,用于演示多数据源数据的保存和查询。

Test实体类:

package com.example.demo.test.data;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "test")
public class Test {

  @Id
  private Integer id;

  public Test(){

  }

  public Integer getId() {
    return this.id;
  }

  public void setId(Integer id){
    this.id = id;
  }
}

Other实体类:

package com.example.demo.other.data;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "other")
public class Other {

  @Id
  private Integer id;

  public Integer getId() {
    return this.id;
  }

  public void setId(Integer id){
    this.id = id;
  }
}

需要注意的是,这两个实体类分属于不同的package,这一点极为重要,spring会根据实体类所属的package来决定用那一个数据源进行操作。

3.建立Repository

分别建立两个实体类对应的Repository,用于进行数据操作。

TestRepository:

package com.example.demo.test.data;

import org.springframework.data.jpa.repository.JpaRepository;

public interface TestRepository extends JpaRepository<Test,Integer> {
}

OtherRepository:

package com.example.demo.other.data;

import org.springframework.data.jpa.repository.JpaRepository;

public interface OtherRepository extends JpaRepository<Other,Integer> {
}

得益于spring-data-jpa优秀的封装,我们只需创建一个接口,就拥有了对实体类的操作能力。

3.对多数据源进行配置

分别对Test和Other两个实体类配置对应的数据源。配置的内容主要包含三个要素:

  1. dataSource,数据源的连接信息
  2. entityManagerFactory,数据处理
  3. transactionManager,事务管理

Test实体类的数据源配置 TestDataConfig:

package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    entityManagerFactoryRef = "entityManagerFactory",basePackages = {"com.example.demo.test.data"}
)
public class TestDataConfig {

  @Autowired
  private JpaProperties jpaProperties;

  @Primary
  @Bean(name = "dataSource")
  @ConfigurationProperties(prefix = "spring.datasource")
  public DataSource dataSource() {
    return DataSourceBuilder.create().build();
  }

  @Primary
  @Bean(name = "entityManagerFactory")
  public LocalContainerEntityManagerFactoryBean entityManagerFactory(
      EntityManagerFactoryBuilder builder,@Qualifier("dataSource") DataSource dataSource) {
    return builder
        .dataSource(dataSource)
        .packages("com.example.demo.test.data")
        .properties(jpaProperties.getHibernateProperties(dataSource))
        .persistenceUnit("test")
        .build();
  }

  @Primary
  @Bean(name = "transactionManager")
  public PlatformTransactionManager transactionManager(
      @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
    return new JpaTransactionManager(entityManagerFactory);
  }

}

代码中的Primary注解表示这是默认数据源。

Other实体类的数据源配置 OtherDataConfig:

package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    entityManagerFactoryRef = "otherEntityManagerFactory",transactionManagerRef = "otherTransactionManager",basePackages = {"com.example.demo.other.data"}
)
public class OtherDataConfig {

  @Autowired
  private JpaProperties jpaProperties;

  @Bean(name = "otherDataSource")
  @ConfigurationProperties(prefix = "other.datasource")
  public DataSource otherDataSource() {
    return DataSourceBuilder.create().build();
  }

  @Bean(name = "otherEntityManagerFactory")
  public LocalContainerEntityManagerFactoryBean otherEntityManagerFactory(
      EntityManagerFactoryBuilder builder,@Qualifier("otherDataSource") DataSource otherDataSource) {
    return builder
        .dataSource(otherDataSource)
        .packages("com.example.demo.other.data")
        .properties(jpaProperties.getHibernateProperties(otherDataSource))
        .persistenceUnit("other")
        .build();
  }

  @Bean(name = "otherTransactionManager")
  public PlatformTransactionManager otherTransactionManager(
      @Qualifier("otherEntityManagerFactory") EntityManagerFactory otherEntityManagerFactory) {
    return new JpaTransactionManager(otherEntityManagerFactory);
  }

}

3.数据操作

我们创建一个Service类TestService来分别对两个数据源进行数据的操作。

package com.example.demo.service;

import com.example.demo.other.data.Other;
import com.example.demo.other.data.OtherRepository;
import com.example.demo.test.data.Test;
import com.example.demo.test.data.TestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class TestService {

  @Autowired
  private TestRepository testRepository;

  @Autowired
  private OtherRepository otherRepository;

  @Value("${name:World}")
  private String name;

  public String getHelloMessage() {
    Test test = new Test();
    test.setId(1);
    test = testRepository.save(test);

    Other other = new Other();
    other.setId(2);
    other = otherRepository.save(other);

    return "Hello " + this.name + " : test's value = " + test.getId() + ",other's value = " + other.getId();

  }

}

对Test和Other分别进行数据插入和读取操作,程序运行后会打印出两个数据源各自的数据。 数据库采用的mysql,连接信息在application.yml进行配置。

spring:
 datasource:
  url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false
  testWhileIdle: true
  validationQuery: SELECT 1 from dual
  username: test
  password: 11111111
  driverClassName: com.mysql.jdbc.Driver
 jpa:
  database: MYSQL
  show-sql: true
  hibernate:
   show-sql: true
   ddl-auto: create
   naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
  properties:
   hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
other:
 datasource:
  url: jdbc:mysql://localhost:3306/other?characterEncoding=utf-8&useSSL=false
  testWhileIdle: true
  validationQuery: SELECT 1
  username: other
  password: 11111111
  driverClassName: com.mysql.jdbc.Driver
 jpa:
  database: MYSQL
  show-sql: true
  hibernate:
   show-sql: true
   ddl-auto: create
   naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
  properties:
   hibernate.dialect: org.hibernate.dialect.MySQL5Dialect

Test实体对应的是主数据源,采用了spring-boot的默认数据源配置项,Other实体单独配置数据源连接。具体应该读取哪一段配置内容,是在配置类OtherDataConfig中这行代码指定的。

@ConfigurationProperties(prefix = "other.datasource")

本示例需要建立的数据库用户和库可以通过以下命令处理:

CREATE USER 'test'@'localhost' IDENTIFIED BY '11111111';
GRANT ALL PRIVILEGES ON *.* TO 'test'@'localhost';
CREATE USER 'other'@'localhost' IDENTIFIED BY '11111111';
GRANT ALL PRIVILEGES ON *.* TO 'other'@'localhost';
create database test;
create database other;

4.总结

spring-data-jpa极大的简化了数据库操作,对于多数据源的支持,也只是需要增加一下配置文件和配置类而已。其中的关键内容有3点:

  1. 配置文件中数据源的配置
  2. 配置类的编写
  3. 实体类所在的package必须与配置类中指定的package一致,如OtherDataConfig中指定的basePackages = {"com.example.demo.other.data"}

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


今天小编给大家分享的是Springboot下使用Redis管道(pipeline)进行批量操作的介绍,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起...
本篇文章和大家了解一下springBoot项目常用目录有哪些。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。springBoot项目常用目录springBoot项...
本篇文章和大家了解一下Springboot自带线程池怎么实现。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。一: ThreadPoolTaskExecuto1 ThreadP...
这篇文章主要介绍了SpringBoot读取yml文件有哪几种方式,具有一定借鉴价值,需要的朋友可以参考下。下面就和我一起来看看吧。Spring Boot读取yml文件的主要方式...
今天小编给大家分享的是SpringBoot配置Controller实现Web请求处理的方法,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧...
本篇文章和大家了解一下SpringBoot实现PDF添加水印的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。简介PDF(Portable Document Form...
本篇文章和大家了解一下解决Springboot全局异常处理与AOP日志处理中@AfterThrowing失效问题的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有...
本篇文章和大家了解一下IDEA创建SpringBoot父子Module项目的实现方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。目录前言1. 软硬件环...
今天小编给大家分享的是springboot获取项目目录路径的方法,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。一定会有所收...
本篇内容主要讲解“SpringBoot+Spring Security无法实现跨域如何解决”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面...
这篇文章主要介绍“vue怎么发送请求到springboot程序”,在日常操作中,相信很多人在vue怎么发送请求到springboot程序问题上存在疑惑,小编查阅了各式资料,整理...
本篇内容主要讲解“Springboot内置的工具类CollectionUtils如何使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家...
本文小编为大家详细介绍“SpringBoot上传文件大小受限如何解决”,内容详细,步骤清晰,细节处理妥当,希望这篇“SpringBoot上传文件大小受限如何解决”文章能帮...
本文小编为大家详细介绍“springboot拦截器如何创建”,内容详细,步骤清晰,细节处理妥当,希望这篇“springboot拦截器如何创建”文章能帮助大家解决疑惑,下面...
本文小编为大家详细介绍“Hikari连接池使用SpringBoot配置JMX监控的方法是什么”,内容详细,步骤清晰,细节处理妥当,希望这篇“Hikari连接池使用SpringBoot配...
今天小编给大家分享一下SpringBoot如何使用Sa-Token实现权限认证的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大...
这篇文章主要介绍“SpringBoot如何集成SFTP客户端实现文件上传下载”,在日常操作中,相信很多人在SpringBoot如何集成SFTP客户端实现文件上传下...
本篇内容主要讲解“Springboot插件怎么开发”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Springboot插件怎
这篇文章主要介绍“Springboot怎么解决跨域请求问题”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇...
今天小编给大家分享一下如何在SpringBoot2中整合Filter的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文...