Spring boot JPA多数据源配置

2021-01-17  本文已影响0人  mua_baby

随便记录一下

环境配置

Spring boot (v2.4.1)
Spring Data JPA 2.4.1

参考:https://www.bilibili.com/video/BV1c54y1C7tV?p=31

image.png

application.yml

server:
  # 后台服务器端口设置为9090
  port: 9090
spring:
  jpa:
    # 当后台逻辑代码crud数据库时,后台日志打印sql
    show-sql: true
    properties:
      hibernate:
        format_sql: true
    hibernate:
      naming:
        # 大小写敏感
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
        #create: 每次应用启动的时候会重新根据实体建立表,之前的表和数据都会被删除。
        #create-drop:和上面的功能一样,但是多了一样,就是在应用关闭的时候,也就是sessionFactory一关闭,会把表删除。
        #update: 最常用的,第一次启动根据实体建立表结构,之后启动会根据实体的改变更新表结构,之前的数据都在。
        #validate: (适用于生产环境)会验证创建数据库表结构,只会和数据库中的表进行比较,
        #           不会创建新表,但是会插入新值,运行程序会校验实体字段与数据库已有的表的字段类型是否相同,不同会报错
      ddl-auto: validate

  datasource:
    primary:
      driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
      username: myusername
      password: mypassword
      jdbc-url: jdbc:sqlserver://localhost:1433;DatabaseName=MydbName;charset=UTF-8
    secondary:
      driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
      username: myusername
      password: mypassword
      jdbc-url: jdbc:sqlserver://localhost:1433;DatabaseName=我的数据库;charset=UTF-8

第一个数据源配置文件JPAPrimaryConfig.java 放在配置类package下。

package com.example.demomultisource.config;
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.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryPrimary",
        transactionManagerRef = "transactionManagerPrimary",
        basePackages = {"com.example.demomultisource.repository.primary"}    // 第一个数据源的 repository包 所在位置
)
public class JPAPrimaryConfig {
    @Resource
    private JpaProperties jpaProperties;
    @Resource
    private HibernateProperties hibernateProperties;
    @Primary
    @Bean(name = "primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource(){
        return DataSourceBuilder.create().build();
    }
    @Primary
    @Bean(name = "entityManagerPrimary")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder){
        return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
    }
    @Primary
    @Bean(name = "entityManagerFactoryPrimary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder){
        Map<String , Object> properties =
                hibernateProperties.determineHibernateProperties(
                        jpaProperties.getProperties(),
                        new HibernateSettings()
                );
        return builder.dataSource(primaryDataSource())
                .properties(properties)
                .packages("com.example.demomultisource.domain.primary")    // 第二个数据源的 domain实体类包 所在位置
                .persistenceUnit("primaryPersistenceUnit")
                .build();
    }
    @Primary
    @Bean(name = "transactionManagerPrimary")
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder){
        return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
    }

}

第二个数据源配置文件JPASecondaryConfig.java 也放在配置类package下。

package com.example.demomultisource.config;
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.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactorySecondary",
        transactionManagerRef = "transactionManagerSecondary",
        basePackages = {"com.example.demomultisource.repository.secondary"}      // 第二个数据源的 repository包 所在位置
)
public class JPASecondaryConfig {
    @Resource
    private JpaProperties jpaProperties;
    @Resource
    private HibernateProperties hibernateProperties;

    @Bean(name = "secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource(){
        return DataSourceBuilder.create().build();
    }

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

    @Bean(name = "entityManagerFactorySecondary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder){
        Map<String , Object> properties =
                hibernateProperties.determineHibernateProperties(
                        jpaProperties.getProperties(),
                        new HibernateSettings()
                );
        return builder.dataSource(secondaryDataSource())
                .properties(properties)
                .packages("com.example.demomultisource.domain.secondary")    // 第二个数据源的 domain实体类包 所在位置
                .persistenceUnit("secondaryPersistenceUnit")
                .build();
    }
    @Bean(name = "transactionManagerSecondary")
    public PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder){
        return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
    }
}
上一篇下一篇

猜你喜欢

热点阅读