Spring Data与多数据源配置

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群版 2核4GB 100GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: Spring Data与多数据源配置

一、项目依赖


首先,我们需要在pom.xml中添加Spring Boot、Spring Data JPA以及数据库驱动的依赖。


<dependencies>
    <!-- Spring Boot Starter Data JPA -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <!-- H2 Database -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
    <!-- MySQL Database -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>


二、配置多数据源


我们将配置两个数据源:一个用于H2数据库,另一个用于MySQL数据库。


1. 配置文件


application.yml中配置数据源信息。


spring:
  datasource:
    h2:
      url: jdbc:h2:mem:testdb
      driver-class-name: org.h2.Driver
      username: sa
      password: password
    mysql:
      url: jdbc:mysql://localhost:3306/testdb
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: password
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        dialect: org.hibernate.dialect.H2Dialect
        format_sql: true


2. 数据源配置类


我们需要为每个数据源创建单独的配置类。


package cn.juwatech.config;
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 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.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {
    @Primary
    @Bean(name = "h2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.h2")
    public DataSource h2DataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "mysqlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.mysql")
    public DataSource mysqlDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Primary
    @Bean(name = "h2EntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean h2EntityManagerFactory(@Qualifier("h2DataSource") DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource);
        em.setPackagesToScan("cn.juwatech.model.h2");
        em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        em.setPersistenceUnitName("h2PU");
        return em;
    }
    @Bean(name = "mysqlEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactory(@Qualifier("mysqlDataSource") DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource);
        em.setPackagesToScan("cn.juwatech.model.mysql");
        em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        em.setPersistenceUnitName("mysqlPU");
        return em;
    }
    @Primary
    @Bean(name = "h2TransactionManager")
    public PlatformTransactionManager h2TransactionManager(@Qualifier("h2EntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
    @Bean(name = "mysqlTransactionManager")
    public PlatformTransactionManager mysqlTransactionManager(@Qualifier("mysqlEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}


3. 启用JPA仓库


为每个数据源分别配置JPA仓库。


package cn.juwatech.config;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EnableJpaRepositories(
        basePackages = "cn.juwatech.repository.h2",
        entityManagerFactoryRef = "h2EntityManagerFactory",
        transactionManagerRef = "h2TransactionManager"
)
@EntityScan(basePackages = "cn.juwatech.model.h2")
public class H2DataSourceConfig {
}
@Configuration
@EnableJpaRepositories(
        basePackages = "cn.juwatech.repository.mysql",
        entityManagerFactoryRef = "mysqlEntityManagerFactory",
        transactionManagerRef = "mysqlTransactionManager"
)
@EntityScan(basePackages = "cn.juwatech.model.mysql")
public class MysqlDataSourceConfig {
}


三、定义实体类


在不同的包中定义不同数据源的实体类。


package cn.juwatech.model.h2;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class H2Entity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    // getters and setters
}
package cn.juwatech.model.mysql;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class MysqlEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    // getters and setters
}


四、定义仓库接口


为每个数据源定义对应的仓库接口。


package cn.juwatech.repository.h2;
import cn.juwatech.model.h2.H2Entity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface H2EntityRepository extends JpaRepository<H2Entity, Long> {
}
package cn.juwatech.repository.mysql;
import cn.juwatech.model.mysql.MysqlEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface MysqlEntityRepository extends JpaRepository<MysqlEntity, Long> {
}


五、测试多数据源配置


最后,我们编写一个测试类,验证多数据源配置是否成功。


package cn.juwatech;
import cn.juwatech.model.h2.H2Entity;
import cn.juwatech.model.mysql.MysqlEntity;
import cn.juwatech.repository.h2.H2EntityRepository;
import cn.juwatech.repository.mysql.MysqlEntityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MultiDataSourceApplication implements CommandLineRunner {
    @Autowired
    private H2EntityRepository h2EntityRepository;
    @Autowired
    private MysqlEntityRepository mysqlEntityRepository;
    public static void main(String[] args) {
        SpringApplication.run(MultiDataSourceApplication.class, args);
    }
    @Override
    public void run(String... args) throws Exception {
        H2Entity h2Entity = new H2Entity();
        h2Entity.setName("H2 Entity");
        h2EntityRepository.save(h2Entity);
        MysqlEntity mysqlEntity = new MysqlEntity();
        mysqlEntity.setName("MySQL Entity");
        mysqlEntityRepository.save(mysqlEntity);
        System.out.println("H2 Entities: " + h2EntityRepository.findAll());
        System.out.println("MySQL Entities: " + mysqlEntityRepository.findAll());
    }
}


总结


通过本文的介绍,我们展示了如何在Spring  Data中配置和使用多个数据源。我们首先配置了数据源,然后为每个数据源创建了单独的配置类和JPA仓库,最后验证了多数据源配置的正确性。这个示例展示了Spring  Boot在处理多数据源时的灵活性和强大功能,希望对大家有所帮助。

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
1天前
|
开发框架 Java 数据库
Spring Boot集成多数据源的最佳实践
Spring Boot集成多数据源的最佳实践
|
1天前
|
前端开发 安全 Java
Spring Boot中的CORS配置
Spring Boot中的CORS配置
|
2天前
|
存储 监控 Java
Spring Cloud Data Flow的实时数据处理
Spring Cloud Data Flow的实时数据处理
|
3天前
|
Java 开发者 Spring
深入理解Spring Boot中的自动配置原理
深入理解Spring Boot中的自动配置原理
|
2天前
|
Java 关系型数据库 测试技术
Spring Boot中实现多数据源配置
Spring Boot中实现多数据源配置
|
2天前
|
缓存 安全 Java
Spring Boot中的自动配置机制详解
Spring Boot中的自动配置机制详解
|
15天前
|
druid Java 关系型数据库
在Spring Boot中集成Druid实现多数据源有两种常用的方式:使用Spring Boot的自动配置和手动配置。
在Spring Boot中集成Druid实现多数据源有两种常用的方式:使用Spring Boot的自动配置和手动配置。
100 5
|
3天前
|
存储 Java 关系型数据库
Spring Data与多数据源配置
Spring Data与多数据源配置
|
7天前
|
Java 数据管理 关系型数据库
Spring Boot中实现多数据源配置
Spring Boot中实现多数据源配置
|
2月前
|
Java 数据库连接 Spring
Spring多数据源配置
Spring多数据源配置