SpringBoot: MyBatis多数据源的用法

一、添加依赖

<?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>cn.edu.tju</groupId>
    <artifactId>springbootmultipledatasource</artifactId>
    <version>1.0-SNAPSHOT</version>


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.7</version>
    </parent>


    <dependencies>
        <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>

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


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

    </dependencies>



</project>

二、在application.properties中配置多个数据源

server.port=9020
spring.datasource.first.url=jdbc:mysql://xxx.xxx.xxx.xxx:3306/test?useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.first.user=root
spring.datasource.first.password=MyPass

spring.datasource.second.url=jdbc:mysql://xxx.xxx.xxx.xxx:3306/appbyte?useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.second.user=root
spring.datasource.second.password=MyPass

三、在多个package里创建多个mapper

package cn.edu.tju.mapper.first;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.Map;


public interface FirstUserMapper {
    @Select("select * from user limit 1")
    Map<String,Object> getUser();
}

package cn.edu.tju.mapper.second;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.Map;


public interface SecondUserMapper {
    @Select("select * from user limit 1")
    Map<String,Object> getUser();
}

四、配置多个数据源

package cn.edu.tju.config;



import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
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 org.springframework.transaction.jta.JtaTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;


@Configuration
public class MyConfig {

    @ConfigurationProperties(prefix = "spring.datasource.first")
    @Bean
    public Properties firstProperties() {
        return new Properties();
    }

    @Bean(name = "firstDataSource")
    @Primary
    public DataSource firstDataSource() {
        HikariDataSource ds = new HikariDataSource();
        ds.setJdbcUrl(firstProperties().getProperty("url"));
        ds.setUsername(firstProperties().getProperty("user"));
        ds.setPassword(firstProperties().getProperty("password"));


        return ds;

    }


    @ConfigurationProperties(prefix = "spring.datasource.second")
    @Bean
    public Properties secondProperties() {
        return new Properties();
    }

    @Bean(name = "secondDataSource")
    public DataSource secondDataSource() {
        HikariDataSource ds = new HikariDataSource();
        ds.setJdbcUrl(secondProperties().getProperty("url"));
        ds.setUsername(secondProperties().getProperty("user"));
        ds.setPassword(secondProperties().getProperty("password"));

        return ds;
    }



    @Bean("firstSqlSessionFactory")
    @Primary
    public SqlSessionFactory firstSqlSessionFactory(){
        try {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(firstDataSource());
            return sqlSessionFactoryBean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Bean("secondSqlSessionFactory")
    public SqlSessionFactory secondSqlSessionFactory(){
        try {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(secondDataSource());
            return sqlSessionFactoryBean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

五、配置多个MapperScan

package cn.edu.tju.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan(basePackages = "cn.edu.tju.mapper.first", sqlSessionFactoryRef = "firstSqlSessionFactory")
public class FirstMapperConfig {
}

package cn.edu.tju.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan(basePackages = "cn.edu.tju.mapper.second", sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondMapperConfig {
}

六、启动类:

package cn.edu.tju;

import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

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

七、controller中使用Mapper

package cn.edu.tju.controller;

import cn.edu.tju.mapper.first.FirstUserMapper;
import cn.edu.tju.mapper.second.SecondUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class DemoController {
    @Autowired
    private FirstUserMapper firstUserMapper;
    @Autowired
    private SecondUserMapper secondUserMapper;


    @RequestMapping("/test1")
    public String test1(){
        Map<String, Object> user = firstUserMapper.getUser();
        return String.valueOf(user.get("username"));
    }


    @RequestMapping("/test2")
    public String test2(){
        Map<String, Object> user = secondUserMapper.getUser();
        return String.valueOf(user.get("username"));
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是SpringBoot整合MyBatis多数据源并用Mapper接口的方式查询数据的代码示例: 首先,在application.properties文件中配置数据源: ``` # 数据源1 spring.datasource.url=jdbc:mysql://localhost:3306/db1 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver # 数据源2 spring.datasource.secondary.url=jdbc:mysql://localhost:3306/db2 spring.datasource.secondary.username=root spring.datasource.secondary.password=123456 spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver ``` 然后,在pom.xml文件中添加MyBatisMyBatis-SpringBoot-Starter依赖: ``` <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> ``` 接下来,创建两个数据源的配置类: ``` @Configuration @MapperScan(basePackages = "com.example.mapper1", sqlSessionTemplateRef = "primarySqlSessionTemplate") public class DataSource1Config { @Bean(name = "primaryDataSource") @ConfigurationProperties(prefix = "spring.datasource") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "primarySqlSessionFactory") public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Bean(name = "primaryTransactionManager") public DataSourceTransactionManager primaryTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "primarySqlSessionTemplate") public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } @Configuration @MapperScan(basePackages = "com.example.mapper2", sqlSessionTemplateRef = "secondarySqlSessionTemplate") public class DataSource2Config { @Bean(name = "secondaryDataSource") @ConfigurationProperties(prefix = "spring.datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "secondarySqlSessionFactory") public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Bean(name = "secondaryTransactionManager") public DataSourceTransactionManager secondaryTransactionManager(@Qualifier("secondaryDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "secondarySqlSessionTemplate") public SqlSessionTemplate secondarySqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } ``` 最后,创建两个Mapper接口: ``` @Mapper public interface UserMapper1 { @Select("SELECT * FROM user") List<User> findAll(); } @Mapper public interface UserMapper2 { @Select("SELECT * FROM user") List<User> findAll(); } ``` 在需要使用数据源1的地方,注入UserMapper1并调用其方法即可: ``` @Service public class UserService1 { @Autowired private UserMapper1 userMapper1; public List<User> findAll() { return userMapper1.findAll(); } } ``` 在需要使用数据源2的地方,注入UserMapper2并调用其方法即可: ``` @Service public class UserService2 { @Autowired private UserMapper2 userMapper2; public List<User> findAll() { return userMapper2.findAll(); } } ``` 希望这个代码示例能够帮到你!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值