springboot jpa设置多数据源

项目使用springboot jpa作为数据持久层,这里记录多数据源配置的信息。

1.数据库配置文件

这里注意spring.datasource.user和spring.datasource.system在后面多数据源配置时需要使用。如果是单一数据源配置,就不需要user和system这一层。

spring:
  datasource:
    user:
      jdbc-url: jdbc:mysql://192.168.1.23:3306/ruizhi_dev?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=CTT
      username: root
      password: Ruizhi@321
      driverClassName: com.mysql.cj.jdbc.Driver
      type: com.zaxxer.hikari.HikariDataSource
      hikari:
        minimum-idle: 5
        maximum-pool-size: 15
        auto-commit: true
        idle-timeout: 30000
        pool-name: DatebookHikariC
        max-lifetime: 120000
        connection-timeout: 30000co
        nnection-test-query: SELECT 1
    system:
      jdbc-url: jdbc:mysql://192.168.1.23:3306/ruizhi_apple?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=CTT
      username: root
      password: Ruizhi@321
      driverClassName: com.mysql.cj.jdbc.Driver
      type: com.zaxxer.hikari.HikariDataSource
      hikari:
        minimum-idle: 5
        maximum-pool-size: 15
        auto-commit: true
        idle-timeout: 30000
        pool-name: DatebookHikariCP
        max-lifetime: 120000
        connection-timeout: 30000
        connection-test-query: SELECT 1
  jpa:
    show-sql: true
    open-in-view: true
    hibernate:
      ddl-auto: update
      use-new-id-generator-mappings: true
      naming:
        implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

2.需要引入的pom依赖

我这里使用的springboot是2.1.13,这个mysql-connector-java默认是8.0.11

 <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

3.DataSourceConfig

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;

/**
 * @description: 多数据源数据库配置
 * @Date: 2020/11/11 14:25
 */
@Configuration
public class DataSourceConfig {

    /**
     * 体系模块的数据源(主数据源)
     * 使用@Primary标记主数据源;主数据源只能有一个
     * @return
     */
    @Primary
    @Bean(name = "systemDataSource")
    @Qualifier("systemDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.system")
    public DataSource userDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 用户模块数据源
     * @return
     */
    @Bean(name = "userDataSource")
    @Qualifier("userDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.user")
    public DataSource systemDataSource() {
        return DataSourceBuilder.create().build();
    }

}

这里注意ConfigurationProperties中的prefix是配置文件中配置的参数,要保持一致。@Bean中的name在下面各自数据源的设置中需要使用。使用@Primary标记主数据源,主数据源只能有一个。

4.SystemRepositoryConfig(主数据有配置)

import com.ruizhi.detection.repository.BaseRepositoryImpl;
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.sql.DataSource;
import java.util.Map;

/**
 * @description: 体系管理的repository配置
 * @Date: 2020/11/11 14:25
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactorySystem",
        transactionManagerRef="transactionManagerSystem",
        //设置Repository所在位置
        basePackages= {"com.ruizhi.detection.repository.systemfile"}, repositoryBaseClass = BaseRepositoryImpl.class)
public class SystemRepositoryConfig {

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

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    private HibernateProperties hibernateProperties;

    /**
     * 使用@Primary标记主数据源
     * @bean中name与顶部配置需要一致
     * @param builder
     * @return
     */
    @Primary
    @Bean(name = "entityManagerFactorySystem")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySystem(
            EntityManagerFactoryBuilder builder) {
        //网上文章大多数都是jpaProperties.getHibernateProperties(dataSource);就直接得到了hibernate的配置map,
        //但这个方法在springboot2.0+好像就舍弃了,所以这里改成这样。
        Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
                jpaProperties.getProperties(), new HibernateSettings());
        return builder.dataSource(systemDataSource).properties(properties)
                //实体包路径
                .packages("com.ruizhi.detection.model.systemfile").build();
    }

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

这里的EnableJpaRepositories中的repositoryBaseClass可以配置也可以不用配置,我这里是有一给封装的,所以进行了配置。

5.UserRepositoryConfig

import com.ruizhi.detection.repository.BaseRepositoryImpl;
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.sql.DataSource;
import java.util.Map;

/**
 * @description: 用户的repository配置
 * @Author: yang.fu.ren
 * @Date: 2020/11/11 14:26
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactoryUser",
        transactionManagerRef="transactionManagerUser",
        //设置Repository所在位置
        basePackages= {"com.ruizhi.detection.repository.user"}, repositoryBaseClass = BaseRepositoryImpl.class)
public class UserRepositoryConfig {

    /**
     * 这里名字与DataSourceConfig中定义的一致
     */
    @Autowired
    @Qualifier("userDataSource")
    private DataSource userDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    private HibernateProperties hibernateProperties;

    @Bean(name = "entityManagerFactoryUser")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryUser(
            EntityManagerFactoryBuilder builder) {
        //网上文章大多数都是jpaProperties.getHibernateProperties(dataSource);就直接得到了hibernate的配置map,
        //但这个方法在springboot2.0+好像就舍弃了,所以这里改成这样。
        Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
                jpaProperties.getProperties(), new HibernateSettings());
        return builder.dataSource(userDataSource).properties(properties)
                //实体的包路径
                .packages("com.ruizhi.detection.model.user").build();
    }

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

6.启动类的配置

启动类中就不需要之前单一数据源设置的那些参数,全部去掉。
之前单一数据源时启动类的配置:
springboot jpa设置多数据源_第1张图片

多数据源的配置:
springboot jpa设置多数据源_第2张图片

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