一、引言

在开发中,我们经常会遇到需要连接多个数据库的情况。使用Spring Boot和MyBatis框架可以很方便地实现多数据源的配置和使用。本文将详细介绍如何在Spring Boot项目中使用多数据源。

二、实操

1、添加所需的依赖:

<!-- Spring Boot Starter for MyBatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>
<!-- 数据库驱动依赖 -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>
<!-- 其他数据库驱动依赖 -->
...

2、配置数据源和MyBatis会话工厂:

在 application.properties 或 application.yml 文件中配置主数据源:

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

 建一个类来配置第二个数据源和MyBatis会话工厂,例如 SecondaryDataSourceConfig

@Configuration
@MapperScan(basePackages = "com.example.secondary", sqlSessionTemplateRef = "secondarySqlSessionTemplate")
public class SecondaryDataSourceConfig {

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

    @Bean(name = "secondarySqlSessionFactory")
    public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(secondaryDataSource);
        return sessionFactory.getObject();
    }

    @Bean(name = "secondarySqlSessionTemplate")
    public SqlSessionTemplate secondarySqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

在 application.properties 或 application.yml 文件中配置第二个数据源:

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

3、创建两个数据库对应的Mapper接口和Mapper XML文件:

主数据源的Mapper接口、Mapper XML文件:

package com.example.primary;

// import语句

@Mapper
public interface PrimaryMapper {
    // 方法定义
}
<!-- primary-mapper.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.primary.PrimaryMapper">
    <!-- SQL语句定义 -->
</mapper>

 第二个数据源的Mapper接口、Mapper XML文件与上面类似,只需将包名、namespace和SQL语句替换为对应的内容。

使用多数据源:

在需要使用主数据源的地方注入 PrimaryMapper

@Autowired
private PrimaryMapper primaryMapper;

 在需要使用第二个数据源的地方注入 SecondaryMapper

@Autowired
private SecondaryMapper secondaryMapper;

 这样,你就可以在Spring Boot项目中使用多个数据源并使用MyBatis进行数据库操作了。需要注意的是,上述示例中使用了两个数据源,你可以根据自己的需求配置更多的数据源,只需按照类似的方式添加配置和代码。

09-08 20:09