springboot + (mysql/pgsql) + jpa 多数据源(不同类数据源)

配置文件:

复制代码
spring:
  datasource:
    primary:
      jdbc-url: jdbc:mysql://host:3306/数据库?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull
      username: 账号
      password: 密码
      driver-class-name: com.mysql.cj.jdbc.Driver

    secondary:
      jdbc-url: jdbc:postgresql://host:3306/数据库
      username: 账号
      password: 密码
      driver-class-name: org.postgresql.Driver

  jpa:
    hibernate:
      primary-dialect: org.hibernate.dialect.MySQL5InnoDBDialect
      secondary-dialect: org.hibernate.spatial.dialect.postgis.PostgisDialect
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        enable_lazy_load_no_trans: true #禁用懒加载
        temp:
          use_jdbc_metadata_defaults: false
        hbm2ddl: 
          auto: none

datasourceconfig:

复制代码
import javax.sql.DataSource;

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;

@Configuration
public class DataSourceConfig {

    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    @Primary
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

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

}

数据源一:

复制代码
import java.util.Map;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
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.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * 数据源一
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryPrimary",
        transactionManagerRef = "transactionManagerPrimary",
        basePackages = {"com.yuruo.reco.entity.repository"
        ,"com.yuruo.reco.entity.mysql.repository"}) //设置Repository所在位置
public class PrimaryConfig {
 
    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource;

    @Autowired
    private JpaProperties jpaProperties;
    @Primary
    @Bean(name = "entityManagerPrimary")
    public EntityManager entityManager() {
        return entityManagerFactoryPrimary().getObject().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactoryPrimary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary() {
    //定义数据库类型和连接方言等主要配置(不写两个数据库方言一样会报错)
        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setGenerateDdl(true);
        jpaVendorAdapter.setDatabase(Database.MYSQL);
        jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5Dialect");
        LocalContainerEntityManagerFactoryBean builder = new LocalContainerEntityManagerFactoryBean();
        builder.setDataSource(primaryDataSource);
        builder.setPackagesToScan("com.yuruo.reco.entity","com.yuruo.reco.entity.mysql");
        builder.setJpaVendorAdapter(jpaVendorAdapter);
        builder.setPersistenceUnitName("primaryPersistenceUnit");
        builder.setJpaPropertyMap(getVendorProperties());
        return builder;
    }

    private Map<String, String> getVendorProperties() {
        return jpaProperties.getProperties();
    }

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

数据源二:

复制代码
import java.util.Map;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
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.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * 数据源二
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactorySecondary", transactionManagerRef = "transactionManagerSecondary", basePackages = {
		"com.yuruo.reco.hologres.repository" }) // 设置Repository所在位置,两个数据库对应的repository和实体类需要不同的路径
public class SecondaryConfig {

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

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

	/**
	 * 将配置文件中对应的配置信息注册到jpa中进行管理
	 * 
	 * @return
	 */
	@Bean(name = "entityManagerFactorySecondary")
	public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary() {
		HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
		jpaVendorAdapter.setGenerateDdl(true);
		jpaVendorAdapter.setDatabase(Database.POSTGRESQL);
		jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.PostgreSQLDialect");
		LocalContainerEntityManagerFactoryBean builder = new LocalContainerEntityManagerFactoryBean();
		builder.setDataSource(secondaryDataSource);
		builder.setPackagesToScan("com.yuruo.reco.hologres.entity");
		builder.setJpaVendorAdapter(jpaVendorAdapter);
		builder.setPersistenceUnitName("secondaryPersistenceUnit");
		builder.setJpaPropertyMap(getVendorProperties());
		return builder;
	}

	@Autowired
	private JpaProperties jpaProperties;

	private Map<String, String> getVendorProperties() {
		return jpaProperties.getProperties();
	}

	// 用来作为数据库事务回滚的限定词
	// @Transactional(rollbackFor = OAPMException.class, value =
	// "transactionManagerSecondary")
	// 事务管理器
	@Bean(name = "transactionManagerSecondary")
	public JpaTransactionManager transactionManagerSecondary() {
		return new JpaTransactionManager(entityManagerFactorySecondary().getObject());
	}
}
相关推荐
逢生博客3 分钟前
Docker 部署RabbitMQ
spring boot·docker·容器·rabbitmq
是阿建吖!1 小时前
【MySQL】数据类型
数据库·mysql
千益1 小时前
【数据库】掌握MySQL事务与锁机制-数据一致性的关键
数据库·mysql
喝醉酒的小白1 小时前
MySQL :参数修改
mysql
权^1 小时前
深入探索Spring Boot 配置文件:类型、加载顺序与最佳实践
java·spring boot·后端
明月看潮生3 小时前
青少年编程与数学 02-011 MySQL数据库应用 03课题、客户端工具
数据库·mysql·青少年编程·编程与数学
4647的码农历程3 小时前
MySQL -- 复合查询
数据库·mysql·oracle
新停浊酒杯3 小时前
基于Spring Boot3 Spring Cloud2023 Spring Cloud Alibaba2023对外提供一个分布式微服务最新基础示例模板
spring boot·spring cloud·微服务
小小鸭程序员4 小时前
Spring Boot 整合 Redis 使用教程
java·spring boot·redis·mysql·spring
秋野酱7 小时前
基于javaweb的SpringBoot个人健康管理系统小程序微信小程序设计与实现(源码+文档+部署讲解)
spring boot·微信小程序·小程序·毕业设计