springboot2.0.5+jpa多数据源配置and注解形式多数据源切换

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 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 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.

注解形式的多数据源切换方式,需要加一个切面,扫描注解,在方法执行前先执行切面里切换数据源的方法,实现动态切换效果,注解多数据源切换代码已上传csdn,demo地址https://download.csdn.net/download/qq_38545713/11219305

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/

 

你可能感兴趣的:(多数据源,多数据源)