Springboot 之 JDBC 多数据源实现

Springboot 中使用 JdbcTemplate 实现多数据源比较简单。查看 JdbcTemplate 源码;可以发现 JdbcTemplate 提供了传入 DataSource 的方式构建不同的 JdbcTemplate 实例。通过该方式就可以实现多数据源。

public JdbcTemplate() {
}

public JdbcTemplate(DataSource dataSource) {
    this.setDataSource(dataSource);
    this.afterPropertiesSet();
}

public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
    this.setDataSource(dataSource);
    this.setLazyInit(lazyInit);
    this.afterPropertiesSet();
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelversion>4.0.0</modelversion>

    <groupid>com.olive</groupid>
    <artifactid>jdbc-multip-datasource</artifactid>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jdbc-multip-datasource</name>
    <url>http://maven.apache.org</url>

    <parent>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-parent</artifactid>
        <version>2.5.14</version>
        <relativepath> <!-- lookup parent from repository -->
    </relativepath></parent>

    <properties>
        <project.build.sourceencoding>UTF-8</project.build.sourceencoding>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-test</artifactid>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupid>mysql</groupid>
            <artifactid>mysql-connector-java</artifactid>
        </dependency>

        <dependency>
            <groupid>org.projectlombok</groupid>
            <artifactid>lombok</artifactid>
        </dependency>

        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
        </dependency>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-jdbc</artifactid>
        </dependency>
    </dependencies>
</project>

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

&#x57FA;&#x672C;&#x914D;&#x7F6E;
server:
  port: 8080

&#x6570;&#x636E;&#x5E93;
spring:
  datasource:
    primary:
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://127.0.0.1:3306/db01?characterEncoding=utf-8&allowMultiQueries=true&autoReconnect=true
      username: root
      password: root
    second:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://127.0.0.1:3306/crm72?characterEncoding=utf-8&allowMultiQueries=true&autoReconnect=true
      username: root
      password: root

DataSourceConfig配置

package com.olive.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 javax.sql.DataSource;

/**
 * @Description: &#x6570;&#x636E;&#x6E90;&#x914D;&#x7F6E;
 */
@Configuration
public class DataSourceConfig {

    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    @Primary
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondDataSource")
    @Qualifier("secondDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource secondDataSource() {
        return DataSourceBuilder.create().build();
    }
}

构建 JdbcTemplateConfig 类

package com.olive.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;

/**
 * @Description: &#x6570;&#x636E;&#x6E90;&#x914D;&#x7F6E;
 * @since
 */
@Configuration
public class JdbcTemplateConfig {

    @Bean(name = "primaryJdbcTemplate")
    public JdbcTemplate primaryJdbcTemplate(
            @Qualifier("primaryDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean(name = "secondJdbcTemplate")
    public JdbcTemplate secondaryJdbcTemplate(
            @Qualifier("secondDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

StudentDO 实体类

package com.olive.entity;

import java.io.Serializable;

import lombok.Data;

@Data
public class StudentDO implements Serializable{

    private Long id;

    private String name;

    private int sex;

    private String grade;
}

TeacherDO 实体类

package com.olive.entity;

import java.io.Serializable;

import lombok.Data;

@Data
public class TeacherDO implements Serializable {

    private Long id;

    private String name;

    private int sex;

    private String office;
}

StudentRepository 类

package com.olive.dao;

import com.olive.entity.TeacherDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.olive.entity.StudentDO;

@Repository
public class StudentRepository {

    @Autowired
    @Qualifier("primaryJdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    public boolean save(StudentDO studentDO) {
        int result =jdbcTemplate.update("INSERT INTO t_student (user_name, sex, grade) VALUES ( ?, ?, ?);",
                studentDO.getName(),
                studentDO.getSex(),
                studentDO.getGrade());
        return result>0;
    }

    public TeacherDO getById(Long id) {
        return jdbcTemplate.queryForObject("select * from t_student where id = ?",
                new BeanPropertyRowMapper<teacherdo>(TeacherDO.class), new Object[]{id});
    }
}
</teacherdo>

TeacherRepository 类

package com.olive.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.olive.entity.TeacherDO;

@Repository
public class TeacherRepository {

    @Autowired
    @Qualifier("secondJdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    public boolean save(TeacherDO teacherDO) {
       int result = jdbcTemplate.update("INSERT INTO t_teacher (user_name, sex, office) VALUES ( ?, ?, ?);",
                teacherDO.getName(),
                teacherDO.getSex(),
                teacherDO.getOffice());
       return result>0;
    }

    public TeacherDO getById(Long id) {
        return jdbcTemplate.queryForObject("select * from t_teacher where id = ?",
                new BeanPropertyRowMapper<teacherdo>(TeacherDO.class), new Object[]{id});
    }
}
</teacherdo>
package com.olive;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author 2230
 *
 */
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }

}
package com.olive;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.olive.entity.StudentDO;
import com.olive.entity.TeacherDO;
import com.olive.dao.StudentRepository;
import com.olive.dao.TeacherRepository;

@SpringBootTest
public class JdbcTest {

    @Autowired
    StudentRepository studentRepository;

    @Autowired
    TeacherRepository teacherRepository;

    @Test
    public void userSave() {
        StudentDO studentDO = new StudentDO();
        studentDO.setName("BUG&#x5F04;&#x6F6E;&#x513F;");
        studentDO.setSex(1);
        studentDO.setGrade("&#x4E00;&#x5E74;&#x7EA7;");
        studentRepository.save(studentDO);

        TeacherDO teacherDO = new TeacherDO();
        teacherDO.setName("Java&#x4E50;&#x56ED;");
        teacherDO.setSex(2);
        teacherDO.setOffice("&#x8BED;&#x6587;");
        teacherRepository.save(teacherDO);
    }
}

Original: https://www.cnblogs.com/happyhuangjinjin/p/16744657.html
Author: BUG弄潮儿
Title: Springboot 之 JDBC 多数据源实现

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/579786/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • Spring Cloud Alibaba 最新版发布!

    大家好,我是栈长。 时隔大半年多,Spring Cloud Alibaba 2021.x 终于发布最新版本了,感谢这位粉丝的通知: 最新版本为 2021.0.4.0,上一个版本还是…

    Java 2023年6月15日
    071
  • Docker安装InfluxDB

    时序型数据库 时序数据库就是存放事件序列数据的数据库,需要支持时序数据的快速写入、持久化、多维度的聚合查询等基本功能。 时间序列数据 时间序列数据是基于时间的一系列数据。在有时间的…

    Java 2023年6月7日
    075
  • Apache Flink系列-①什么是Apache Flink?

    Apache Flink系列-①什么是Apache Flink? Apache Flink是一个框架和分布式处理引擎,用于在无界和有界数据流上进行有状态计算。Flink被设计为在所…

    Java 2023年6月5日
    077
  • S

    第一部分:基础——增删查改【第一章】做好准备 Getting Started (时长25分钟)【第二章】在单一表格中检索数据 Retrieving Data From a Sing…

    Java 2023年6月7日
    078
  • Leetcode链表

    Leetcode链表 边学边刷的……慢慢写慢慢更 题干: 思路: 删除链表节点,就多了一个判断等值。 由于是单向链表,所以要删除节点时要找到目标节点的上一个…

    Java 2023年6月7日
    077
  • 彩食鲜架构团队风采

    2020-4-15 架构组支援福州做冷热数据拆分 4-24 听说最近测试环境不稳定,首席掏腰包请大家喝个茶吧~~ ps: 服务器资源不足,咋办? :) 4-25 诸事不顺,上天台聊…

    Java 2023年6月8日
    066
  • 代码审查:从 ArrayList 说线程安全

    本文从代码审查过程中发现的一个 ArrayList 相关的「线程安全」问题出发,来剖析和理解线程安全。 案例分析 前两天在代码 Review 的过程中,看到有小伙伴用了类似以下的写…

    Java 2023年6月5日
    094
  • HTML基本标记

    头部标记 说明:元素的作用范围是整篇文档。元素中可以有元信息定义、文档样式表定义和脚本等信息,定义在HTML语言头部的内容往往不会在网页上直接显示。 标题标记 说明:在标记中间的就…

    Java 2023年6月5日
    0125
  • 注释和良好的编程风格

    注释、良好的编程风格 注释 &#x5206;&#x7C7B;&#xFF1A; &#x5355;&#x884C;&#x6CE8;&am…

    Java 2023年6月7日
    066
  • 戏说领域驱动设计(廿二)——聚合

    聚合的自白 大家好,我是聚合,在你们的期盼之下我终于出来了。其实早就想和大家见一面,不过作者每天总想着水流量,到现在才让我出来。他把实体和值对象这两个我家庭内的成员先介绍让我感觉非…

    Java 2023年6月7日
    054
  • Redis之ziplist源码分析

    一、ziplist简介 从上一篇分析我们知道quicklist的底层存储使用了ziplist(压缩列表),由于压缩列表本身也有不少内容,所以重新开了一篇,在正式源码之前,还是先看下…

    Java 2023年6月6日
    078
  • mycat 生产环境 cpu 占用 800% 问题 Mycat调优启用useOffHeapForMerge报java.lang.NumberFormatException异常解决(附源码)

    最近发现kunshan这家的生产环境进程mycat cpu 800%然后mycat基本上就假死了,无法查询了。 后来回忆部署这家生产环境的时候,因为服务器内存大于等于64G 然后m…

    Java 2023年5月29日
    068
  • [学习笔记] Java异常处理

    程序运行时,可能会发生各种错误,一些错误是可以避免的,还有些错误是随机出现的且不可避免,一个健壮的程序必须能够处理这些错误; Java内置一套异常处理机制,使用异常来表示错误; 异…

    Java 2023年6月5日
    076
  • nginx配置常用 ( 反向代理时传客户端IP )

    反向代理时传客户端IP csharp;gutter:true;location / { proxy_set_header X-Forwarded-For $remote_addr;…

    Java 2023年5月30日
    050
  • Git配置用户信息和SSH免密

    一、配置用户信息 1.查看配置信息 查看所有配置 $ git config -l/–list 查看系统配置 $ git config –system -l/–list 查看用…

    Java 2023年6月8日
    077
  • Win10文件、文件夹被占用解决方法

    有时删除文件/弹出移动硬盘的时候会出现文件或文件夹或磁盘被占用的情况,从而无法删除文件/文件夹或安全弹出移动硬盘。这时可以在资源管理器中搜索该文件、文件夹,来找到对应的程序。使用了…

    Java 2023年6月9日
    067
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球