spring boot mysql mybits 多数据库

本文详细介绍如何在Spring Boot项目中配置多个MySQL数据库,并通过MyBatis进行操作。包括Maven依赖配置、application.properties设置、数据源及MyBatis配置等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、使用场景

在开发产品的过程中,经常会遇到需要配置多数据库的情况,这篇文章记录一下怎么配置多mysql数据库,mybits配置,手动连接mysql总是感觉开发效率不是很高。

2、添加maven依赖包

maven的pom文件如下

<?xml version="1.0" encoding="UTF-8"?>
<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>dotamore</groupId>
    <artifactId>mutidb</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>mutidb</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

3、配置application.properties文件

配置两个数据库连接

# test1库
spring.datasource.db1.url=jdbc:mysql://127.0.0.1:3306/test1?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=true
spring.datasource.db1.username=root
spring.datasource.db1.password=pwd
spring.datasource.db1.driver-class-name=com.mysql.cj.jdbc.Driver
# test2库
spring.datasource.db2.url=jdbc:mysql://127.0.0.1:3306/test2?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=true
spring.datasource.db2.username=root
spring.datasource.db2.password=pwd
spring.datasource.db2.driver-class-name=com.mysql.cj.jdbc.Driver

4、修改启动类,关闭数据源自动配置选项

其实就是将@SpringBootApplication修改为@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
启动类如下:

package dotamore.mutidb;

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

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class MutidbApplication {
    public static void main(String[] args) {
        SpringApplication.run(MutidbApplication.class, args);
    }
}

5、数据源配置

一共需要写3个配置类,主要作用是将application.properties的数据库称映射成java bean对象,再制定bean对应的mybaits数据库接口包的目录。三个配置类代码如下
5.1、映射application.properties的数据库为bean对象

DataSourceConfig类

package dotamore.mutidb;

import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

//被自动扫描
@Configuration
public class DataSourceConfig {

    @Bean(name = "db1")//对应配置文件的spring.datasource.db1
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public DataSource dataSource1() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "db2")//对应配置文件的spring.datasource.db2
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource dataSource2() {
        return DataSourceBuilder.create().build();
    }

}

MybatisDbAConfig类

package dotamore.mutidb;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;

//配置mybatis的接口所在的目录
@Configuration
@MapperScan(basePackages = {"dotamore.mutidb.db1"}, sqlSessionFactoryRef = "sqlSessionFactory1")
public class MybatisDbAConfig {

    @Autowired
    @Qualifier("db1")
    private DataSource ds1;

    @Bean
    public SqlSessionFactory sqlSessionFactory1() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(ds1);
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate1() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory1()); // 使用上面配置的Factory
        return template;
    }
}

MybatisDbBConfig类

package dotamore.mutidb;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"dotamore.mutidb.db2"}, sqlSessionFactoryRef = "sqlSessionFactory2")
public class MybatisDbBConfig {

    @Autowired
    @Qualifier("db2")
    private DataSource ds2;

    @Bean
    public SqlSessionFactory sqlSessionFactory2() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(ds2);
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate2() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory2());
        return template;
    }
}

6、测试案例
经过上面5个步骤已经配置完成了,测试测试db1使用能正常使用即可,在test1数据库中有一张match_video_queue的表格,包含一个int和一个long字段,其对应的java 实体类对象如下:

MatchVideoQueue类

package dotamore.mutidb.entity;

public class MatchVideoQueue {

    public int id;

    public long match_id;

    @Override
    public String toString() {
        return "MatchVideoQueue{" +
                "id=" + id +
                ", match_id=" + match_id +
                '}';
    }
}

在包dotamore.mutidb.db1下写一个接口MVMapper,查询数据

package dotamore.mutidb.db1;

import dotamore.mutidb.entity.MatchVideoQueue;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.ArrayList;

@Mapper
public interface MVMapper {

    @Select("select id ,match_id from match_video_queue")
    ArrayList<MatchVideoQueue> getMatchInfo();

}

最后写一个测试类,TestConfig

package dotamore.mutidb;

import dotamore.mutidb.entity.MatchVideoQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import dotamore.mutidb.db1.MVMapper;

import java.util.ArrayList;

@RestController
public class TestConfig {

    @Autowired
    MVMapper mvMapper;

    @RequestMapping("/xiao")
    public String xiao(){
        ArrayList<MatchVideoQueue> amv = mvMapper.getMatchInfo();
        System.out.println(amv.size());
        return  "hehe";
    }
}

测试结果如下图所示,最终成功地获取了数据:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值