1. 程式人生 > 其它 >SpringBoot + JPA 配置雙資料來源

SpringBoot + JPA 配置雙資料來源

一、首先配置application.yml

server:
  port: 8081
  servlet:
    context-path: /

  #是否開啟壓縮,預設false
  compression:
    enabled: true
    #執行壓縮的閥值,預設2048,單位:位元組B
    min-response-size: 2048
    #指定要壓縮的MIME type,多個以逗號分隔,[text/html, text/xml, text/plain, text/css, text/javascript, application/javascript, application/json, application/xml]
    mime
-types: application/json,application/xml,text/html,text/xml,text/plain spring: application: name: chint-kml-api datasource: ds1: driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://xx:3306/chiticbank?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=UTC
username: xx password: xx@123 ds2: driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://xx:3306/smartpower?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai username: xx password: xx@123456 type: com.zaxxer.hikari.HikariDataSource hikari: minimum
-idle: 5 maximum-pool-size: 15 auto-commit: true idle-timeout: 30000 pool-name: DatebookHikariCP max-lifetime: 1800000 connection-timeout: 30000 connection-test-query: SELECT 1 jpa: show-sql: true hibernate: ddl-auto: update database-platform: org.hibernate.dialect.MySQL5InnoDBDialect database: mysql

二、使用配置類讀取application.yml配置的兩個資料來源,並將其注入到Spring的IOC容器中

package com.chint.kml.api.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;
 
 
@Configuration
public class DataSourceConfig {
 
    @Bean(name = "ds1DataSource")
    @Qualifier("ds1DataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.ds1")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
 
    @Bean(name = "ds2DataSource")
    @Qualifier("ds2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.ds2")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
 
}

三、配置兩個資料來源

(一):資料來源1

package com.chint.kml.api.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
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.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryDs1",
        transactionManagerRef = "transactionManagerDs1",
        basePackages = {"com.chint.kml.api.repository.rep1"})
public class Ds1Config {

    @Autowired
    @Qualifier("ds1DataSource")
    private DataSource ds1Datasource;

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    private HibernateProperties hibernateProperties;

    private Map<String, Object> getVendorProperties() {
        return hibernateProperties.determineHibernateProperties(
                jpaProperties.getProperties(), new HibernateSettings());
    }

    @Bean(name = "entityManagerDs1")
    @Primary
    public EntityManager entityManagerDs1(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryDs1(builder).getObject().createEntityManager();
    }

    /**
     * 設定實體類所在位置
     */
    @Bean(name = "entityManagerFactoryDs1")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryDs1(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(ds1Datasource)
                .packages("com.chint.kml.api.repository.rep1")
                .persistenceUnit("ds1PersistenceUnit")
                .properties(getVendorProperties())
                .build();
    }

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

}

(二):資料來源2

package com.chint.kml.api.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
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.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryDs2",
        transactionManagerRef = "transactionManagerDs2",
        basePackages = {"com.chint.kml.api.repository.rep2"})
public class Ds2Config {

    @Autowired
    @Qualifier("ds2DataSource")
    private DataSource ds2Datasource;

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    private HibernateProperties hibernateProperties;

    private Map<String, Object> getVendorProperties() {
        return hibernateProperties.determineHibernateProperties(
                jpaProperties.getProperties(), new HibernateSettings());
    }

    @Bean(name = "entityManagerDs2")
    public EntityManager entityManagerDs2(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryDs2(builder).getObject().createEntityManager();
    }

    /**
     * 設定實體類所在位置
     */
    @Bean(name = "entityManagerFactoryDs2")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryDs2(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(ds2Datasource)
                .packages("com.chint.kml.api.repository.rep2")
                .persistenceUnit("ds2PersistenceUnit")
                .properties(getVendorProperties())
                .build();
    }

    @Bean(name = "transactionManagerDs2")
    public PlatformTransactionManager transactionManagerDs2(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryDs2(builder).getObject());
    }

}

四、啟動類主函式入口

SpringBoot啟動類需關閉註解 ,程式啟動載入的倉庫(@EnableJpaRepositories),因為在資料來源配置類中已經開啟了
@SpringBootApplication
//@EnableJpaRepositories
@ComponentScan(CoreConstants.BASE_PACKAGE)
public class ChintKmlApiServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(ChintKmlApiServiceApplication.class, args);
        LoadPoints loadPoints = SpringUtils.getBean(LoadPoints.class);
        loadPoints.loadPoints();
    }

}

注意:springboot版本

2.3.8.RELEASE