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)

大家都在看

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