精品专区-精品自拍9-精品自拍三级乱伦-精品自拍视频-精品自拍视频曝光-精品自拍小视频

網站建設資訊

NEWS

網站建設資訊

SpringBoot項目中的多數據源支持的方法

1.概述

歷下網站制作公司哪家好,找創新互聯公司!從網頁設計、網站建設、微信開發、APP開發、響應式網站設計等網站項目制作,到程序開發,運營維護。創新互聯公司從2013年成立到現在10年的時間,我們擁有了豐富的建站經驗和運維經驗,來保證我們的工作的順利進行。專注于網站建設就選創新互聯公司。

項目中經常會遇到一個應用需要訪問多個數據源的情況,本文介紹在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 {
}

OtherRepository:

package com.example.demo.other.data;

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

public interface OtherRepository extends JpaRepository {
}

得益于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"}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持創新互聯。


本文題目:SpringBoot項目中的多數據源支持的方法
網站鏈接:http://m.jcarcd.cn/article/jdjchg.html
主站蜘蛛池模板: 91高清视频 | 露脸国产| 成人国产 | 国产尹人在线视 | 日本免费一二区 | 九九色综| 国产91视频| 日本成人区 | 国产视频一区四区 | 琪琪色好看在线观看 | 日本三级在线播 | 日本系列1 | 国产精品露脸国 | 91人成亚| 人人摸人人草 | 国产精品爽妇网 | 老熟妻色毛茸茸 | 成人午夜福利群爱片 | 最新国产精品拍自在线观看 | 国产未成女一区二区 | 日本亲近相奷中 | 日韩欧美亚洲精品 | 国产系列ts在 | 欧美日韩亚州 | 国产日韩成 | 日本女性车厢的概况 | 国产91剧情 | 日韩成人免费 | 欧洲精品欧美精品 | 国产美女91| 国产末成年女噜噜 | 欧美另类video | 91精品综合| 三级在线播放 | 国产精品视频观看 | 欧美日韩一卡二区 | 国产精品精品国内 | 91秦先生久 | 日韩成人午夜福利 | 91日本免费高清 | 成人播放日韩在线观 |