springboot jdbctemplate 实现多数据源

1.简介:

所谓多数据源,其实就是在一个项目中使用多个数据库实例中的数据库或者同一个数据库实例中多个不同的库。
在大部分情况下会使用更加强大的持久化框架来访问数据库,比如MyBatis、Hibernate或者Spring Data JPA等ORM框架。使用JDBC是开发者必备的基础技能,只有熟悉了基础的JDBC,才能更加深入地学习其他的ORM框架。

2.举例

2.1配置多数据源连接信息

spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/jdbctest
spring.datasource.primary.username=root
spring.datasource.primary.password=Yjb123456
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/jdbctest2
spring.datasource.secondary.username=root
spring.datasource.secondary.password=Yjb123456
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver

2.2配置JDBC初始化
创建DataSourceConfig类,在项目启动时读取配置文件中的数据库信息,并对JDBC初始化,具体代码如下:
在上面的示例中,DataSourceConfig类的作用是在项目启动时根据特定的前缀加载不同的数据源,再根据构建好的数据源创建不同的JdbcTemplate。由于Spring容器中存在两个数据源,使用默认的类型查找时会报错,因此加上@Qualifier注解,表示按照名称查找。这里创建了两个JdbcTemplate实例,分别对应了两个数据源。
需要注意的是,使用多个数据源时需要添加@Primary注解,表示自动装配出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者。Primary表示“主要的”,类似于SQL语句中的“Primary Key”(主键),只能有唯一一个,否则会报错。

package com.yangjunbo.helloword.properties;

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 org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfig {
    @Primary
    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix="spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "secondaryDataSource")
    @Qualifier("secondaryDataSource")
    @ConfigurationProperties(prefix="spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name="primaryJdbcTemplate")
    public JdbcTemplate primaryJdbcTemplate (
            @Qualifier("primaryDataSource") DataSource dataSource ) {
        return new JdbcTemplate(dataSource);
    }
    @Bean(name="secondaryJdbcTemplate")
    public JdbcTemplate secondaryJdbcTemplate(
            @Qualifier("secondaryDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

2.3测试调用多数据源

package com.yangjunbo.helloword;

import com.yangjunbo.helloword.pojo.Student;
import com.yangjunbo.helloword.rowMapper.StudentRowMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest
public class RowMapper {
   
    @Autowired
    private JdbcTemplate primaryJdbcTemplate;

    @Autowired
    private JdbcTemplate secondaryJdbcTemplate;

    @Test
    public void dataSourceTest(){
        Student student = new Student("weiz多数据源",0,30);
        primaryJdbcTemplate.update("INSERT INTO Student(name, sex, age) values(?, ?, ?)",
                student.getName(), student.getSex(), student.getAge());

        secondaryJdbcTemplate.update("INSERT INTO Student(name, sex, age) values(?, ?, ?)",
                student.getName(), student.getSex(), student.getAge());
    }
}

参考书籍《springboot从入门到实战-章为忠著》

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot是一个非常流行并且易于使用的后端框架。在传统的数据库应用程序中,我们通常都需要使用JdbcTemplate来操作数据库。但是在某些情况下,我们需要动态切换数据源。比如,我们可能要从单一的应用程序中连接到不同的数据源(例如生产环境与测试环境)。 为了解决这一问题,我们可以在SpringBoot中使用DynamicDataSource这个开源项目来实现动态切换数据源。 在使用DynamicDataSource之前,我们需要先在application.properties文件中配置我们的数据源。比如,我们可以配置两个数据源: ``` spring.datasource.primary.url=jdbc:mysql://localhost:3306/db1 spring.datasource.primary.username=root spring.datasource.primary.password=root spring.datasource.secondary.url=jdbc:mysql://localhost:3306/db2 spring.datasource.secondary.username=root spring.datasource.secondary.password=root ``` 然后我们在代码中实现DynamicDataSource的相关接口,实现动态切换数据源的功能。具体来说,我们需要实现AbstractRoutingDataSource这个类中的determineCurrentLookupKey()方法,这个方法的返回值决定了当前应该使用哪个数据源。 接下来,我们可以在代码中使用@Autowired注解来注入DynamicDataSource,然后根据需要调用DynamicDataSource的setDataSource()方法来切换数据源,从而实现动态切换数据源。 总之,使用SpringBootJdbcTemplate结合DynamicDataSource能够非常方便地实现动态切换数据源的功能,从而提高代码的灵活性和可维护性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值