SpringBoot Mybatis多数据源配置

项目依赖springboot2+mybatis+mysql

首先在mysql中创建数据库db1和db2,然后分别在两个数据库中创建表student1和studnet2并插入演示数据

create DATABASE db1;
use db1;
create table student1(
	name varchar(100) not null,
    age int
);
insert into student1(name,age) values('张三',18);

create DATABASE db2;
use db2;
create table student2(
	name varchar(100) not null,
    age int
);
insert into student2(name,age) values('李四',20);

创建springboot项目并导入mybatis和mysql依赖

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

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

项目结构
![](https://img-blog.csdnimg.cn/20200223122247233.p

application.properties配置数据源

spring.datasource.db1.jdbc-url=jdbc:mysql://localhost:3306/db1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.db1.username=root
spring.datasource.db1.password=root
spring.datasource.db1.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.db2.jdbc-url=jdbc:mysql://localhost:3306/db2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.db2.username=root
spring.datasource.db2.password=root
spring.datasource.db2.driver-class-name=com.mysql.cj.jdbc.Driver

MybatisMysqlOneConfig.java

package com.example.config;

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.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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.example.mapper.db1", sqlSessionTemplateRef = "db1SessionTemplate")
public class MybatisMysqlOneConfig {
    @Bean(name = "db1")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public DataSource db1() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public SqlSessionFactory db1SessionFactory(@Qualifier("db1") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //添加XML目录
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/db1/**/*Mapper.xml"));
        return bean.getObject();
    }

    @Bean
    @Primary
    public DataSourceTransactionManager db1TransactionManager(@Qualifier("db1") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    @Primary
    public SqlSessionTemplate db1SessionTemplate(@Qualifier("db1SessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

MybatisMysqlTwoConfig.java

package com.example.config;

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.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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.example.mapper.db2", sqlSessionTemplateRef = "db2SessionTemplate")
public class MybatisMysqlTwoConfig {
    @Bean(name = "db2")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource db2() {
        return DataSourceBuilder.create().build();
    }
    @Bean
    public SqlSessionFactory db2SessionFactory(@Qualifier("db2") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/db2/**/*Mapper.xml"));
        return bean.getObject();
    }

    @Bean
    public DataSourceTransactionManager db2TransactionManager(@Qualifier("db2") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate db2SessionTemplate(@Qualifier("db2SessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

这里用了两个数据库进行演示,如果还要其它的可以继续按上面示例增加类和application.properties数据库配置,@Primary只需指定其中一个数据库就行

Student.java

package com.example.entity;

public class Student {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

StudentDB1Mapper.java

package com.example.mapper.db1;

import com.example.entity.Student;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface StudentDB1Mapper {
    @Select("select * from student1")
    List<Student> getStudents();
}

StudentDB2Mapper.java

package com.example.mapper.db2;

import com.example.entity.Student;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface StudentDB2Mapper {
    @Select("select * from student2")
    List<Student> getStudents();
}

StudentService.java

package com.example.Service;

import com.example.entity.Student;
import com.example.mapper.db1.StudentDB1Mapper;
import com.example.mapper.db2.StudentDB2Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentService {
    @Autowired
    private StudentDB1Mapper studentDB1Mapper;

    @Autowired
    private StudentDB2Mapper studentDB2Mapper;

    public void getStudents() {
        List<Student> students1 = studentDB1Mapper.getStudents();
        List<Student> students2 = studentDB2Mapper.getStudents();

        System.out.println("数据源DB1:" + students1);
        System.out.println("数据源DB2:" + students2);
    }


}

StudentController.java

package com.example.controller;

import com.example.Service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;

    @RequestMapping("/getStudents")
    public void getStudents() {
        studentService.getStudents();
    }
}

最后启动项目,浏览器访问http://localhost:8080/getStudents看打印结果
在这里插入图片描述

发布了3 篇原创文章 · 获赞 0 · 访问量 3608

猜你喜欢

转载自blog.csdn.net/qq_40548741/article/details/104362580