1. 程式人生 > >springboot2.0.5+jpa多資料來源配置

springboot2.0.5+jpa多資料來源配置

1.首先配置資料來源連線總裝類DataSourcesConfig

package com.cpic.dataSources;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
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;

@Configuration
public class DataSourcesConfig {

    /**
     * 第一個資料來源總裝類
     * @return
     */
    @Primary//表示為預設資料來源,必須要有一個預設的資料來源
    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix = "spring.primary.datasource")//指定第一個資料來源的名稱
    public DataSource primaryDataSource() {
        System.out.println("第1個數據源連線成功!");
        //1.5.x版本的與2.0.x版本的配置這裡不同
        /**
         * springboot1.5.x版本的方式DataSourceBuilder.create().build();
         * springboot2.0.x版本的阿方式primaryDataSourceProperties().initializeDataSourceBuilder().build();
         */
        return primaryDataSourceProperties().initializeDataSourceBuilder().build();
    }


    @Primary
    @Bean(name = "primaryDataSourceProperties")
    @Qualifier("primaryDataSourceProperties")
    @ConfigurationProperties(prefix = "spring.primary.datasource")
    public DataSourceProperties primaryDataSourceProperties() {
        System.out.println("111111111111");
        return new DataSourceProperties();
    }




    /**
     * 第二個資料來源總裝類
     * @return
     */
    @Bean(name = "secondaryDataSource")
    @Qualifier("secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.secondary.datasource")//指定第二個資料來源的名稱
    public DataSource secondaryDataSource() {
        System.out.println("第2個數據源連線成功!");
        //1.5.x版本的與2.0.x版本的配置這裡不同
        /**
         * springboot1.5.x版本的方式DataSourceBuilder.create().build();
         * springboot2.0.x版本的阿方式primaryDataSourceProperties().initializeDataSourceBuilder().build();
         */
        return secondaryDataSourceProperties().initializeDataSourceBuilder().build();
    }

    @Bean(name = "secondaryDataSourceProperties")
    @Qualifier("secondaryDataSourceProperties")
    @ConfigurationProperties(prefix = "spring.secondary.datasource")
    public DataSourceProperties secondaryDataSourceProperties() {
        System.out.println("222222222222222222");
        return new DataSourceProperties();
    }



}

2.其次分別配置每個資料來源的連線類(第一個資料來源PrimaryConfig)

package com.cpic.dataSources;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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="entityManagerFactoryPrimary",
    transactionManagerRef="transactionManagerPrimary",
    basePackages= {"com.cpic.repository.repository1"})//掃描jpa的sql語句的包
public class PrimaryConfig {

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


    @Autowired(required=false)
    private JpaProperties jpaProperties;


    @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)
            //設定實體類所在位置
            .packages("com.cpic.domain")
            .persistenceUnit("primaryPersistenceUnit")
            .properties(getVendorProperties())
            .build();
    }


    //1.5.x版本的與2.0.x版本的配置這裡不同
    private Map<String, Object> getVendorProperties() {
        /**
         * springboot1.5.x版本的方式jpaProperties.getHibernateProperties(new DataSource());
         * springboot2.0.x版本的阿方式jpaProperties.getHibernateProperties(new HibernateSettings());
         */
        return jpaProperties.getHibernateProperties(new HibernateSettings());
    }

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

}

3.其次分別配置每個資料來源的連線類(第二個資料來源SecondaryConfig)

package com.cpic.dataSources;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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="entityManagerFactorySecondary",
    transactionManagerRef="transactionManagerSecondary",
    basePackages= { "com.cpic.repository.repository2" })//掃描jpa的sql語句的包
public class SecondaryConfig {

    @Autowired
    private JpaProperties jpaProperties;

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

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

    @Bean(name = "entityManagerFactorySecondary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder) {
        return builder
            .dataSource(secondaryDataSource)
            .packages("com.cpic.domain.test2")
            .persistenceUnit("secondaryPersistenceUnit")
            .properties(getVendorProperties())
            .build();
    }

    //1.5.x版本的與2.0.x版本的配置這裡不同
    private Map<String, Object> getVendorProperties() {
        /**
         * springboot1.5.x版本的方式jpaProperties.getHibernateProperties(new DataSource());
         * springboot2.0.x版本的阿方式jpaProperties.getHibernateProperties(new HibernateSettings());
         */
        return jpaProperties.getHibernateProperties(new HibernateSettings());
    }

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

}

4.最後看一下配置檔案資料庫配置

spring:
   
    primary:
        datasource:
                type: com.zaxxer.hikari.HikariDataSource
                url: jdbc:mysql://localhost:3306/ccp_local?useUnicode=true&characterEncoding=utf8&useSSL=false
                username: root
                password: root
    secondary:
        datasource:
                type: com.zaxxer.hikari.HikariDataSource
                url: jdbc:mysql://localhost:3306/ccp_record?useUnicode=true&characterEncoding=utf8&useSSL=false
                username: root
                password: root
    jpa:
        database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
        database: MYSQL
        show-sql: true
        properties:
            hibernate.id.new_generator_mappings: true
            hibernate.cache.use_second_level_cache: true
            hibernate.cache.use_query_cache: false
            hibernate.generate_statistics: true
            hibernate.cache.region.factory_class: com.hazelcast.hibernate.HazelcastCacheRegionFactory
            hibernate.cache.hazelcast.instance_name: RecordingService
            hibernate.cache.use_minimal_puts: true
            hibernate.cache.hazelcast.use_lite_member: true
#        關閉自動建表
        hibernate:
            ddl-auto: update

6.參考地址

1.5.x版本
https://blog.csdn.net/qq_41690306/article/details/79304501
2.0.x版本
https://blog.csdn.net/u011751078/article/details/79803248

Spring-data-jpa支援和JdbcTemplate兩種方式配置多資料來源連線
http://blog.didispace.com/springbootmultidatasource/