SpringBoot中mybatis配置多数据源

首先需要创建多个数据库

简单的user表

CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

导入项目依赖

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

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

application.properties


spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.one.username=root
spring.datasource.one.password=feng10.10
spring.datasource.one.url=jdbc:mysql://localhost:3306/m_1?characterEncoding=utf8&serverTimezone=UTC

spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.two.username=root
spring.datasource.two.password=feng10.10
spring.datasource.two.url=jdbc:mysql://localhost:3306/m_2?characterEncoding=utf8&serverTimezone=UTC


# 多数据源配置时,mybatis这里设置的配置是不生效的!!
#mybatis.mapper-locations=classpath*:/mapper1/*.xml, classpath*:/mapper2/*.xml
#mybatis.type-aliases-package=com.zlf.mybatisDemo.domain

手动配置数据源

DataSourceConfig.java

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
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 {

    //将配置文件中对应的属性注入改数据源中
    @ConfigurationProperties("spring.datasource.one")
    @Bean
    DataSource dsOne(){
        return DruidDataSourceBuilder.create().build();
    }
    //将配置文件中对应的属性注入改数据源中
    @ConfigurationProperties("spring.datasource.two")
    @Bean
    DataSource dsTwo(){
        return DruidDataSourceBuilder.create().build();
    }
}

手动配置myBatis配置

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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.annotation.Resource;
import javax.sql.DataSource;


/**
 * 配置myBaits配置 1
 * 在@MapperScan注解中指定Mapper接口所在的位直, 同时指定SqlSessionFactory的实例名, 则该位置下的 Mapper将使用 SqlSessionFactory 实例。
 * 提供 SqlSessionFactory 的实例, 直接创建出来, 同时将 DataSource 的实例设置给 SqlSessionFactory,
 * 这里创建的 SqlSessionFactory 实例也就是@MapperScan 注解中 sqlSessionFactoryRef参数指定的实例 。
 */
@Configuration
@MapperScan(value = "com.zlf.mybatisDemo.mapper1",sqlSessionFactoryRef = "sqlSessionFactoryBean1")
public class MyBatisConfigOne {

    @Resource(name = "dsOne")
    DataSource dataSource;

    /**
     * 提供 SqlSessionFactory 的实例, 直接创建出来, 同时将 DataSource 的实例设置给 SqlSessionFactory,
     * 这里创建的 SqlSessionFactory 实例也就是@MapperScan 注解中 sqlSessionFactoryRef参数指定的实例 。
     * @return
     * @throws Exception
     */
    @Bean
    SqlSessionFactory sqlSessionFactoryBean1() throws Exception{
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        // 需要手动设置mapper文件的路径
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper1/*.xml"));
        return factoryBean.getObject();
    }

    /**
     * 提供一个 SqlSessionTemplate 实例。 这是一个线程安全类,主要用来管理 MyBatis 中的 SqlSession 操作。
     * @return
     * @throws Exception
     */
    @Bean
    SqlSessionTemplate sqlSessionTemplate1() throws Exception{
        return new SqlSessionTemplate(sqlSessionFactoryBean1());
    }

}
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.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * 配置myBaits配置 2
 * 在@MapperScan注解中指定Mapper接口所在的位直, 同时指定SqlSessionFactory的实例名, 则该位置下的 Mapper将使用 SqlSessionFactory 实例。
 * 提供 SqlSessionFactory 的实例, 直接创建出来, 同时将 DataSource 的实例设置给 SqlSessionFactory,
 * 这里创建的 SqlSessionFactory 实例也就是@MapperScan 注解中 sqlSessionFactoryRef参数指定的实例 。
 */
@Configuration
@MapperScan(value = "com.zlf.mybatisDemo.mapper2",sqlSessionFactoryRef = "sqlSessionFactoryBean2")
public class MyBatisConfigTwo {

    @Resource(name = "dsTwo")
    DataSource dataSource;


    /**
     * 提供 SqlSessionFactory 的实例, 直接创建出来, 同时将 DataSource 的实例设置给 SqlSessionFactory,
     * 这里创建的 SqlSessionFactory 实例也就是@MapperScan 注解中 sqlSessionFactoryRef参数指定的实例 。
     * @return
     * @throws Exception
     */
    @Bean
    SqlSessionFactory sqlSessionFactoryBean2() throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 需要手动设置mapper文件的路径
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper2/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * 提供一个 SqlSessionTemplate 实例。 这是一个线程安全类,主要用来管理 MyBatis 中的 SqlSession 操作。
     * @return
     * @throws Exception
     */
    @Bean
    SqlSessionTemplate sqlSessionTemplate2() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryBean2());
    }

}

项目结构

启动类

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

@SpringBootApplication

//@MapperScan(basePackages = {"com.zlf.mybatisDemo.mapper1","com.zlf.mybatisDemo.mapper2"}) 已经在配置类中设置了
public class MybatisDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisDemoApplication.class, args);
    }

}

测试结果

测试类

import com.zlf.mybatisDemo.domain.User;
import com.zlf.mybatisDemo.mapper1.userMapper1;
import com.zlf.mybatisDemo.mapper2.userMapper2;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class MybatisDemoApplicationTests {

    @Autowired
    userMapper1 userMapper1;
    @Autowired
    userMapper2 userMapper2;

    @Test
    void TestMybatis(){
        List<User> users1 = userMapper1.findAll();

        List<User> users2 = userMapper2.findAll();

        System.out.println("第一个数据源:m_1");

        System.out.println(users1);


        System.out.println("第二个数据源:m_2");
        System.out.println(users2);
    }


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值