• Springboot 之 JPA 多数据源实现


    简介

    微服务推崇单服务单数据库;但是还是免不了存在一个微服务连接多个数据库的情况,今天介绍一下如何使用 JPA 的多数据源。主要采用将不同数据库的 Repository 接口分别存放到不同的 package,Spring 去扫描不同的包,注入不同的数据源来实现多数据源。

    创建 jpa-multip-datasource 项目
    分别创建db01和db02数据库

    学生表 t_student

    1. CREATE TABLE `t_student` (
    2. `id`  int(11) NOT NULL AUTO_INCREMENT ,
    3. `user_name`  varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
    4. `sex`  int(1) NULL DEFAULT NULL ,
    5. `grade`  varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
    6. PRIMARY KEY (`id`)
    7. )
    8. ENGINE=InnoDB
    9. DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
    10. AUTO_INCREMENT=1 ROW_FORMAT=DYNAMIC;

    教师表 t_teacher

    1. CREATE TABLE `t_teacher` (
    2. `id`  int(11) NOT NULL AUTO_INCREMENT ,
    3. `user_name`  varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
    4. `sex`  int(1) NULL DEFAULT NULL ,
    5. `office`  varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
    6. PRIMARY KEY (`id`)
    7. )
    8. ENGINE=InnoDB
    9. DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
    10. AUTO_INCREMENT=1 ROW_FORMAT=DYNAMIC;
    pom.xml文件引入如下依赖
    1. "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    2.  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    3.  4.0.0
    4.  com.olive
    5.  jpa-multip-datasource
    6.  0.0.1-SNAPSHOT
    7.  jar
    8.  jpa-multip-datasource
    9.  http://maven.apache.org
    10.  
    11.   org.springframework.boot
    12.   spring-boot-starter-parent
    13.   2.5.14
    14.    
    15.  
    16.  
    17.   UTF-8
    18.   8
    19.   8
    20.  
    21.  
    22.   
    23.    org.springframework.boot
    24.    spring-boot-starter-test
    25.    test
    26.   
    27.   
    28.    org.springframework.boot
    29.    spring-boot-starter-data-jpa
    30.   
    31.   
    32.    mysql
    33.    mysql-connector-java
    34.   
    35.   
    36.    org.projectlombok
    37.    lombok
    38.   
    39.  
    配置两个数据源

    分别为第一个主数据源(primary),第二数据源(second),具体配置如下:

    1. # 基本配置
    2. server:
    3.   port: 8080
    4. # 数据库
    5. spring:
    6.   jpa:
    7.     show-sql: true
    8.     database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    9.     hibernate:
    10.       ddl-auto: update
    11.   datasource:
    12.     primary:
    13.       driver-class-name: com.mysql.jdbc.Driver
    14.       jdbc-url: jdbc:mysql://127.0.0.1:3306/db01?characterEncoding=utf-8&allowMultiQueries=true&autoReconnect=true
    15.       username: root
    16.       password: root
    17.     sencond:
    18.       driver-class-name: com.mysql.cj.jdbc.Driver
    19.       jdbc-url: jdbc:mysql://127.0.0.1:3306/db02?characterEncoding=utf-8&allowMultiQueries=true&autoReconnect=true
    20.       username: root
    21.       password: root
    22.   jackson:
    23.     serialization:
    24.       indent-output: true
    配置数据源

    DataSourceConfig 配置

    1. /**
    2.  * @Description: 数据源配置
    3.  */
    4. @Configuration
    5. public class DataSourceConfig {
    6.     @Bean(name = "primaryDataSource")
    7.     @Qualifier("primaryDataSource")
    8.     @ConfigurationProperties(prefix = "spring.datasource.primary")
    9.     @Primary
    10.     public DataSource primaryDataSource() {
    11.         return DataSourceBuilder.create().build();
    12.     }
    13.     @Bean(name = "secondDataSource")
    14.     @Qualifier("secondDataSource")
    15.     @ConfigurationProperties(prefix = "spring.datasource.sencond")
    16.     public DataSource secondDataSource() {
    17.         return DataSourceBuilder.create().build();
    18.     }
    19. }

    PrimaryConfig数据源

    1. /**
    2.  * @Description: 主数据源配置
    3.  * @date
    4.  */
    5. @Configuration
    6. @EnableTransactionManagement
    7. @EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryPrimary",
    8.                         transactionManagerRef = "transactionManagerPrimary",
    9.                         basePackages = {"com.olive.repository.primary"})
    10. public class PrimaryConfig {
    11.     @Autowired
    12.     @Qualifier("primaryDataSource")
    13.     private DataSource primaryDataSource;
    14.     @Autowired
    15.     private HibernateProperties hibernateProperties;
    16.     @Autowired
    17.     private JpaProperties jpaProperties;
    18.     @Primary
    19.     @Bean(name = "entityManagerPrimary")
    20.     public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
    21.         return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
    22.     }
    23.     @Primary
    24.     @Bean(name = "entityManagerFactoryPrimary")    //primary实体工厂
    25.     public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
    26.         return builder.dataSource(primaryDataSource)
    27.                 .properties(getHibernateProperties())
    28.                 .packages("com.olive.entity.primary")     //换成你自己的实体类所在位置
    29.                 .persistenceUnit("primaryPersistenceUnit")
    30.                 .build();
    31.     }
    32.     @Primary
    33.     @Bean(name = "transactionManagerPrimary")
    34.     public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
    35.         return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
    36.     }
    37.     private Map getHibernateProperties() {
    38.         return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
    39.     }
    40. }

    SecondConfig 数据源源

    1. /**
    2.  * @Description: 第二个数据源配置
    3.  */
    4. @Configuration
    5. @EnableTransactionManagement
    6. @EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactorySecond",
    7.                         transactionManagerRef = "transactionManagerSecond",
    8.                         basePackages = {"com.olive.repository.second"})
    9. public class SecondConfig {
    10.     @Autowired
    11.     @Qualifier("secondDataSource")
    12.     private DataSource secondDataSource;
    13.     @Resource
    14.     private JpaProperties jpaProperties;
    15.     @Resource
    16.     private HibernateProperties hibernateProperties;
    17.     @Bean(name = "entityManagerSecond")
    18.     public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
    19.         return entityManagerFactorySecond(builder).getObject().createEntityManager();
    20.     }
    21.     @Bean(name = "entityManagerFactorySecond")    //primary实体工厂
    22.     public LocalContainerEntityManagerFactoryBean entityManagerFactorySecond (EntityManagerFactoryBuilder builder) {
    23.         return builder.dataSource(secondDataSource)
    24.                 .properties(getHibernateProperties())
    25.                 .packages("com.olive.entity.second")     //换成你自己的实体类所在位置
    26.                 .persistenceUnit("secondaryPersistenceUnit")
    27.                 .build();
    28.     }
    29.     @Bean(name = "transactionManagerSecond")
    30.     public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
    31.         return new JpaTransactionManager(entityManagerFactorySecond(builder).getObject());
    32.     }
    33.     private Map getHibernateProperties() {
    34.         return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
    35.     }
    36. }
    创建学生与老师实体类

    Student实体类

    1. package com.olive.entity.primary;
    2. import java.io.Serializable;
    3. import javax.persistence.Column;
    4. import javax.persistence.Entity;
    5. import javax.persistence.GeneratedValue;
    6. import javax.persistence.GenerationType;
    7. import javax.persistence.Id;
    8. import lombok.Data;
    9. @Data
    10. @Entity(name="t_student")
    11. public class StudentDO implements Serializable{
    12.     @Id
    13.     @GeneratedValue(strategy = GenerationType.IDENTITY)
    14.     private Long id;
    15.     @Column(name = "user_name"// 若实体属性和表字段名称一致时,可以不用加@Column注解
    16.     private String name;
    17.     @Column(name = "sex")
    18.     private int sex;
    19.     
    20.     @Column(name = "grade")
    21.     private String grade;
    22. }

    Teacher实体类

    1. package com.olive.entity.second;
    2. import java.io.Serializable;
    3. import javax.persistence.Column;
    4. import javax.persistence.Entity;
    5. import javax.persistence.GeneratedValue;
    6. import javax.persistence.GenerationType;
    7. import javax.persistence.Id;
    8. import lombok.Data;
    9. @Data
    10. @Entity(name="t_teacher")
    11. public class TeacherDO implements Serializable {
    12.  @Id
    13.  @GeneratedValue(strategy = GenerationType.IDENTITY)
    14.  private Long id;
    15.  @Column(name = "user_name"// 若实体属性和表字段名称一致时,可以不用加@Column注解
    16.  private String name;
    17.  @Column(name = "sex")
    18.  private int sex;
    19.  
    20.  @Column(name = "office")
    21.  private String office;
    22. }
    数据库持久类

    StudentRepository类

    1. package com.olive.repository.primary;
    2. import org.springframework.data.jpa.repository.JpaRepository;
    3. import org.springframework.stereotype.Repository;
    4. import com.olive.entity.primary.StudentDO;
    5. @Repository
    6. public interface StudentRepository extends JpaRepository {
    7. }

    TeacherRepository类

    1. package com.olive.repository.second;
    2. import org.springframework.data.jpa.repository.JpaRepository;
    3. import org.springframework.stereotype.Repository;
    4. import com.olive.entity.second.TeacherDO;
    5. @Repository
    6. public interface TeacherRepository extends JpaRepository {
    7. }
    创建springboot引导类
    1. package com.olive;
    2. import org.springframework.boot.SpringApplication;
    3. import org.springframework.boot.autoconfigure.SpringBootApplication;
    4. @SpringBootApplication
    5. public class Application {
    6.     public static void main(String[] args) {
    7.         SpringApplication.run(Application.class);
    8.     }
    9. }
    测试
    1. package com.olive;
    2. import org.junit.jupiter.api.Test;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.boot.test.context.SpringBootTest;
    5. import com.olive.entity.primary.StudentDO;
    6. import com.olive.entity.second.TeacherDO;
    7. import com.olive.repository.primary.StudentRepository;
    8. import com.olive.repository.second.TeacherRepository;
    9. @SpringBootTest
    10. public class JpaTest {
    11.  @Autowired
    12.  StudentRepository studentRepository;
    13.  @Autowired
    14.  TeacherRepository teacherRepository;
    15.  @Test
    16.  public void userSave() {
    17.   StudentDO studentDO = new StudentDO();
    18.   studentDO.setName("BUG弄潮儿");
    19.   studentDO.setSex(1);
    20.   studentDO.setGrade("一年级");
    21.   studentRepository.save(studentDO);
    22.   TeacherDO teacherDO = new TeacherDO();
    23.   teacherDO.setName("Java乐园");
    24.   teacherDO.setSex(2);
    25.   teacherDO.setOffice("语文");
    26.   teacherRepository.save(teacherDO);
    27.  }
    28. }

    记得点「」和「在看」↓

    爱你们

  • 相关阅读:
    神经网络中常见的超参数,神经网络参数个数计算
    zabbix二级目录反代部署
    基础组件-流量回放(全链路流量回放预研)
    OLAP介绍
    Python | 排列与组合
    蓝桥杯(3.12)
    【机器学习】svm
    【目标检测】利用PyQT5搭建YOLOv5可视化界面
    Docker最基本使用
    分享一个追剧神器(不是看剧),可以追电视剧、动漫和电影
  • 原文地址:https://blog.csdn.net/huangjinjin520/article/details/126801377