首页 > 其他分享 >Springboot 之 JDBC 多数据源实现

Springboot 之 JDBC 多数据源实现

时间:2022-09-30 13:44:27浏览次数:52  
标签:JDBC Springboot 数据源 springframework import olive org com public

简介

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();
}

pom.xml文件引入如下依赖

<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 -->
	</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),具体配置如下:

# 基本配置
server:
  port: 8080

# 数据库
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: 数据源配置
 */
@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: 数据源配置
 * @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});
    }
}

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});
    }
}

创建springboot引导类

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弄潮儿");
		studentDO.setSex(1);
		studentDO.setGrade("一年级");
		studentRepository.save(studentDO);

		TeacherDO teacherDO = new TeacherDO();
		teacherDO.setName("Java乐园");
		teacherDO.setSex(2);
		teacherDO.setOffice("语文");
		teacherRepository.save(teacherDO);
	}
}

标签:JDBC,Springboot,数据源,springframework,import,olive,org,com,public
From: https://www.cnblogs.com/happyhuangjinjin/p/16744657.html

相关文章

  • 学习笔记:springBoot整合七牛云
    在项目开发的过程中,文件存储是一大问题,本人遇到的情况是服务器的操作系统从原来的Linux变成了windowServer,但是,自己写的文件上传具有SFTP功能,服务器对于一些路径出现了乱......
  • SpringBoot集成Dubbo案例
    SpringBoot集成Dubbo:Case​​1、什么是Duubo?​​​​2、概念架构​​​​2.1提供者​​​​2.2消费者​​​​2.3注册中心​​​​3、SpringBoot集成Dubbo步骤​​​​:o......
  • SpringBoot文件上传深入浅出
    前言文件上传原理浏览器发起HTTPPOST请求,指定请求头:Content-Type:multipart/form-dataContent-Type:指定了文件类型服务端解析请求内容,执行文件保存处理,返回成功消息。不......
  • 2022-09-30 数据源对象,容器
    目录spring数据源对象管理DruidDataSourceComboPooledDataSource加载properties文件容器创建容器获取bean核心容器总结容器相关bean相关依赖注入相关spring数据源对象管......
  • SpringBoot之Mybatis开启SQL记录和Pagehelper
    配置mybatismybatis:#mapper路径mapper-locations:classpath:mapper/*.xmlconfiguration:#日志输出log-impl:org.apache.ibatis.logging.stdout.StdO......
  • SpringBoot2 不同版本中 文件上传大小配置
    由于springboot具有几个版本,不同版本对于文件上传最大限制的配置也有所不同。所以要注意springboot本身的版本,不然会一直报错#在springboot1.3版本中:multipart.maxFil......
  • JDBC介绍及使用
    JDBC简介JDBC(JavaDataBaseConnectivity,java数据库连接)是一种用于执行SQL语句的JavaAPI,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDB......
  • Springboot从入门到精通
    SpringBoot创建SpringBoot有两种创建方法,一种是在IDEA中创建,一种是在Spring官网创建,两种方法是一样的,但是需要联网。SpringBoot项目快速启动1.对SpringBoot项目打包(执行......
  • springboot发送邮件
    springboot发送邮件简化版:1.pom.xml引入依赖<!--e-mail--><dependency><groupId>com.sun.mail</groupId><artifactId>java......
  • 用spring 创建ComboPooledDataSource和JdbcTemplate对象
    用spring创建ComboPooledDataSource和JdbcTemplate对象3.1添加ioc相关jar包 <dependency><groupId>org.springframework</groupId><artifactId>spring-core<......