最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot項目中的多數(shù)據(jù)源支持的方法

 更新時間:2017年10月23日 10:08:13   作者:QiHaiYan  
本篇文章主要介紹了SpringBoot項目中的多數(shù)據(jù)源支持的方法,主要介紹在SpringBoot項目中利用SpringDataJpa技術(shù)如何支持多個數(shù)據(jù)庫的數(shù)據(jù)源,有興趣的可以了解一下

1.概述

項目中經(jīng)常會遇到一個應(yīng)用需要訪問多個數(shù)據(jù)源的情況,本文介紹在SpringBoot項目中利用SpringDataJpa技術(shù)如何支持多個數(shù)據(jù)庫的數(shù)據(jù)源。

具體的代碼參照該 示例項目

2.建立實體類(Entity)

首先,我們創(chuàng)建兩個簡單的實體類,分別屬于兩個不同的數(shù)據(jù)源,用于演示多數(shù)據(jù)源數(shù)據(jù)的保存和查詢。

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會根據(jù)實體類所屬的package來決定用那一個數(shù)據(jù)源進行操作。

3.建立Repository

分別建立兩個實體類對應(yīng)的Repository,用于進行數(shù)據(jù)操作。

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優(yōu)秀的封裝,我們只需創(chuàng)建一個接口,就擁有了對實體類的操作能力。

3.對多數(shù)據(jù)源進行配置

分別對Test和Other兩個實體類配置對應(yīng)的數(shù)據(jù)源。配置的內(nèi)容主要包含三個要素:

  1. dataSource,數(shù)據(jù)源的連接信息
  2. entityManagerFactory,數(shù)據(jù)處理
  3. transactionManager,事務(wù)管理

Test實體類的數(shù)據(jù)源配置 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注解表示這是默認數(shù)據(jù)源。

Other實體類的數(shù)據(jù)源配置 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.數(shù)據(jù)操作

我們創(chuàng)建一個Service類TestService來分別對兩個數(shù)據(jù)源進行數(shù)據(jù)的操作。

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分別進行數(shù)據(jù)插入和讀取操作,程序運行后會打印出兩個數(shù)據(jù)源各自的數(shù)據(jù)。 數(shù)據(jù)庫采用的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實體對應(yīng)的是主數(shù)據(jù)源,采用了spring-boot的默認數(shù)據(jù)源配置項,Other實體單獨配置數(shù)據(jù)源連接。具體應(yīng)該讀取哪一段配置內(nèi)容,是在配置類OtherDataConfig中這行代碼指定的。

@ConfigurationProperties(prefix = "other.datasource")

本示例需要建立的數(shù)據(jù)庫用戶和庫可以通過以下命令處理:

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.總結(jié)

spring-data-jpa極大的簡化了數(shù)據(jù)庫操作,對于多數(shù)據(jù)源的支持,也只是需要增加一下配置文件和配置類而已。其中的關(guān)鍵內(nèi)容有3點:

  1. 配置文件中數(shù)據(jù)源的配置
  2. 配置類的編寫
  3. 實體類所在的package必須與配置類中指定的package一致,如OtherDataConfig中指定的basePackages = {"com.example.demo.other.data"}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 詳解Spring Retry實現(xiàn)原理

    詳解Spring Retry實現(xiàn)原理

    這篇文章主要介紹了詳解Spring Retry實現(xiàn)原理,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-04-04
  • java Hibernate 一對多自身關(guān)聯(lián)問題

    java Hibernate 一對多自身關(guān)聯(lián)問題

    formBean在提交表單的時候,域中數(shù)據(jù)庫在下一次中仍然保留引起的,struts formBean 默認的scope為session,手動設(shè)置為request,就好了
    2008-07-07
  • Spring Boot2.3 新特性分層JAR的使用

    Spring Boot2.3 新特性分層JAR的使用

    這篇文章主要介紹了Spring Boot2.3 新特性分層JAR的使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • Spring Security如何在Servlet中執(zhí)行

    Spring Security如何在Servlet中執(zhí)行

    這篇文章主要介紹了Spring Security如何在Servlet中執(zhí)行,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-04-04
  • Spring中的@ExceptionHandler異常攔截器

    Spring中的@ExceptionHandler異常攔截器

    這篇文章主要介紹了Spring中的@ExceptionHandler異常攔截器,Spring的@ExceptionHandler可以用來統(tǒng)一處理方法拋出的異常,給方法加上@ExceptionHandler注解,這個方法就會處理類中其他方法拋出的異常,需要的朋友可以參考下
    2024-01-01
  • Java算法之遞歸算法計算階乘

    Java算法之遞歸算法計算階乘

    這篇文章主要為大家詳細介紹了Java遞歸算法計算階乘,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2015-08-08
  • Nacos作為配置中心注冊監(jiān)聽器方法

    Nacos作為配置中心注冊監(jiān)聽器方法

    本文主要討論Nacos作為配置中心時,其中配置內(nèi)容發(fā)生更改時,我們的應(yīng)用程序能夠做的事。一般使用監(jiān)聽器來實現(xiàn)這步操作,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧
    2023-02-02
  • Springboot2.0配置JPA多數(shù)據(jù)源連接兩個mysql數(shù)據(jù)庫方式

    Springboot2.0配置JPA多數(shù)據(jù)源連接兩個mysql數(shù)據(jù)庫方式

    這篇文章主要介紹了Springboot2.0配置JPA多數(shù)據(jù)源連接兩個mysql數(shù)據(jù)庫方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • mybatis一直加載xml,找到錯誤的解決方案

    mybatis一直加載xml,找到錯誤的解決方案

    這篇文章主要介紹了mybatis一直加載xml,找到錯誤的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • Java基礎(chǔ)之命名規(guī)范的詳解

    Java基礎(chǔ)之命名規(guī)范的詳解

    這篇文章主要介紹了Java基礎(chǔ)之命名規(guī)范的詳解,文中有非常詳細的代碼示例,對正在學(xué)習(xí)Java基礎(chǔ)的小伙伴們有很好地幫助,需要的朋友可以參考下
    2021-05-05

最新評論

呼玛县| 中超| 诸城市| 伽师县| 霞浦县| 林芝县| 邵阳市| 阿鲁科尔沁旗| 肇州县| 佛学| 霞浦县| 海丰县| 陈巴尔虎旗| 琼结县| 阿拉尔市| 康定县| 巩留县| 汪清县| 荥阳市| 和田县| 津南区| 全椒县| 盐津县| 六安市| 永州市| 嘉荫县| 天柱县| 金寨县| 嘉黎县| 厦门市| 肃宁县| 达孜县| 疏勒县| 咸丰县| 曲水县| 通榆县| 平邑县| 东台市| 宁城县| 六安市| 南康市|