当前位置:   article > 正文

Springboot 之 JPA 多数据源实现

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. <project xmlns="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.  <modelVersion>4.0.0</modelVersion>
  4.  <groupId>com.olive</groupId>
  5.  <artifactId>jpa-multip-datasource</artifactId>
  6.  <version>0.0.1-SNAPSHOT</version>
  7.  <packaging>jar</packaging>
  8.  <name>jpa-multip-datasource</name>
  9.  <url>http://maven.apache.org</url>
  10.  <parent>
  11.   <groupId>org.springframework.boot</groupId>
  12.   <artifactId>spring-boot-starter-parent</artifactId>
  13.   <version>2.5.14</version>
  14.   <relativePath /> <!-- lookup parent from repository -->
  15.  </parent>
  16.  <properties>
  17.   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  18.   <maven.compiler.source>8</maven.compiler.source>
  19.   <maven.compiler.target>8</maven.compiler.target>
  20.  </properties>
  21.  <dependencies>
  22.   <dependency>
  23.    <groupId>org.springframework.boot</groupId>
  24.    <artifactId>spring-boot-starter-test</artifactId>
  25.    <scope>test</scope>
  26.   </dependency>
  27.   <dependency>
  28.    <groupId>org.springframework.boot</groupId>
  29.    <artifactId>spring-boot-starter-data-jpa</artifactId>
  30.   </dependency>
  31.   <dependency>
  32.    <groupId>mysql</groupId>
  33.    <artifactId>mysql-connector-java</artifactId>
  34.   </dependency>
  35.   <dependency>
  36.    <groupId>org.projectlombok</groupId>
  37.    <artifactId>lombok</artifactId>
  38.   </dependency>
  39.  </dependencies>
  40. </project>
配置两个数据源

分别为第一个主数据源(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<String, Object> 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<String, Object> 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<StudentDO, Long> {
  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<TeacherDO, Long> {
  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. }

记得点「」和「在看」↓

爱你们

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/52310
推荐阅读
相关标签
  

闽ICP备14008679号