13.SpringBoot学习(十三)——JDBC之 Spring Boot Jpa多数据源

本文档详细介绍了如何在Spring Boot项目中配置和使用JPA实现多数据源。通过创建MasterConfiguration和SlaveConfiguration两个配置类,分别管理masterDataSource和slaveDataSource,并在各自的repository中进行操作。测试类UserRepositoryTest展示了查询方法的正确执行。
摘要由CSDN通过智能技术生成

1.简介

1.1 概述

在实际项目中一般是一个数据源,但是在某些特殊场景可能需要多个数据源,这里以 spring boot jpa 为例演示一下多数据源的配置和使用。

2.演示环境

  1. JDK 1.8.0_201
  2. Spring Boot 2.2.0.RELEASE
  3. 构建工具(apache maven 3.6.3)
  4. 开发工具(IntelliJ IDEA )

3.演示代码

3.1 代码说明

配置两个数据源,分别是 masterDataSource 和 slaveDataSource,它们由两个配置类 MasterConfiguration 和 SlaveConfiguration 来加载,分别扫描不同路径下的 repository。最后通过测试类来调用。

3.2 代码结构

image-20200727200503199

3.3 maven 依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

3.4 配置文件

application.properties

# master 数据源
spring.datasource.master.jdbc-url=jdbc:mysql://172.16.11.125:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.master.username=root
spring.datasource.master.password=123456
spring.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver

# slave 数据源
spring.datasource.slave.jdbc-url=jdbc:mysql://172.16.11.125:3306/test_jpa?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.slave.username=root
spring.datasource.slave.password=123456
spring.datasource.slave.driver-class-name=com.mysql.cj.jdbc.Driver

# 打印sql、自动建表、格式化sql
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.hbm2ddl.auto=create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

# 日志打印
logging.level.root=INFO
logging.level.org.hibernate=INFO
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
logging.level.org.hibernate.type.descriptor.sql.BasicExtractor=TRACE
logging.level.com.soulballad.usage=DEBUG

3.5 java代码

UserModel.java

@Entity
@Table(name = "t_user")
public class UserModel {
   
    @Id
    @GeneratedValue
    private Long id;
    @Column(nullable 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值