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());
	}
}

### Spring Boot 多数据源配置 (MySQLPostgreSQL) 在现代应用程序开发中,Spring Boot 提供了一种简单而高效的方式来管理和配置多个数据源。以下是关于如何在 Spring Boot 中配置和使用 MySQLPostgreSQL 的具体方法。 #### 1. 添加必要的依赖项 为了支持多数据源功能,需要引入相应的 JDBC 驱动程序以及 MyBatis 或 JPA 等持久化工具的支持。以下是在 `pom.xml` 文件中的依赖声明: ```xml <dependencies> <!-- MySQL Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- PostgreSQL Driver --> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> <!-- Spring Data JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- MyBatis Support (Optional) --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.3.0</version> </dependency> </dependencies> ``` 上述代码片段展示了所需的 Maven 依赖项[^2]。 --- #### 2. 配置数据源属性 在 `application.properties` 或 `application.yml` 文件中定义两个数据源的相关参数。例如,在 YAML 格式下可如下设置: ```yaml spring: datasource: mysql: url: jdbc:mysql://localhost:3306/db_mysql?useSSL=false&serverTimezone=UTC username: root password: secret driver-class-name: com.mysql.cj.jdbc.Driver postgresql: url: jdbc:postgresql://localhost:5432/db_postgres username: postgres password: admin driver-class-name: org.postgresql.Driver ``` 此部分描述了如何为 MySQLPostgreSQL 定义各自的连接字符串和其他必要信息[^1]。 --- #### 3. 创建自定义的数据源 Bean 通过 Java 配置分别创建针对 MySQLPostgreSQL 的 `DataSource` 实例,并将其注册到 Spring 应用上下文中。 ##### (1)MySQL 数据源配置 ```java import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MysqlConfig { @Bean(name = "mysqlDataSource") public DataSource mysqlDataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/db_mysql?useSSL=false&serverTimezone=UTC"); dataSource.setUsername("root"); dataSource.setPassword("secret"); return dataSource; } } ``` ##### (2)PostgreSQL 数据源配置 ```java import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class PostgresqlConfig { @Bean(name = "postgresDataSource") public DataSource postgresDataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUrl("jdbc:postgresql://localhost:5432/db_postgres"); dataSource.setUsername("postgres"); dataSource.setPassword("admin"); return dataSource; } } ``` 这些代码片段说明了如何手动构建并注入特定于每种数据库型的 `DataSource` 对象[^3]。 --- #### 4. 设置实体管理器工厂和事务管理器 为了让每个数据源都能独立工作,还需要分别为其配置对应的 `EntityManagerFactory` 和 `TransactionManager`。 ##### (1)MySQL 相关组件 ```java import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; @EnableTransactionManagement @Configuration public class MysqlJpaConfig { private final DataSource mysqlDataSource; public MysqlJpaConfig(@Qualifier("mysqlDataSource") DataSource mysqlDataSource) { this.mysqlDataSource = mysqlDataSource; } @Primary @Bean(name = "entityManagerFactory") public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) { return builder.dataSource(mysqlDataSource).packages("com.example.mysql").build(); } @Primary @Bean(name = "transactionManager") public PlatformTransactionManager transactionManager( EntityManagerFactoryBuilder builder, @Qualifier("mysqlDataSource") DataSource mysqlDataSource) { return new JpaTransactionManager(entityManagerFactory(builder).getObject()); } } ``` ##### (2)PostgreSQL 相关组件 ```java import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; @EnableTransactionManagement @Configuration public class PostgresqlJpaConfig { private final DataSource postgresDataSource; public PostgresqlJpaConfig(@Qualifier("postgresDataSource") DataSource postgresDataSource) { this.postgresDataSource = postgresDataSource; } @Bean(name = "pgsqlEntityManagerFactory") public LocalContainerEntityManagerFactoryBean pgsqlEntityManagerFactory(EntityManagerFactoryBuilder builder) { return builder.dataSource(postgresDataSource).packages("com.example.pgsql").build(); } @Bean(name = "pgsqlTransactionManager") public PlatformTransactionManager pgsqlTransactionManager( EntityManagerFactoryBuilder builder, @Qualifier("postgresDataSource") DataSource postgresDataSource) { return new JpaTransactionManager(pgsqlEntityManagerFactory(builder).getObject()); } } ``` 以上两段代码解释了如何为不同数据源分配专属的实体管理器和事务处理器[^4]。 --- #### 总结 完成上述步骤后即可成功实现基于 Spring Boot 的双数据源架构设计。这种方案允许开发者在同一项目内同时访问 MySQLPostgreSQL 数据库资源,满足复杂的业务需求场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值