Springboot MybatisPlus整合多数据源

一、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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>multiple-data-sources</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>multiple-data-sources</name>
    <description>Demo project for Spring Boot</description>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- mybatisplus 生成工具 -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.72</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.example.multipledatasources.MultipleDataSourcesApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

二、创建数据表

为了演示方便,这里创建三个数据库,数据库中表创建一样的。

1、数据库如下图自行创建

2、创建表

CREATE TABLE `ht_student` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

三、多数据源DataSource配置类

咱们配置了三个数据源,所以配置三个类

1、数据源一:MysqlDataSourceConfig主数据源



import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
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.orm.mysql1.mapper", sqlSessionFactoryRef = "sqlSessionFactory1")
public class MysqlDataSourceConfig {
    @Primary
    @Bean(name = "mysqlDataSource1")
    @ConfigurationProperties(prefix = "spring.datasource.mysql")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "sqlSessionFactory1")
    public SqlSessionFactory sqlSessionFactory1(@Qualifier("mysqlDataSource1") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/mysql1/*Mapper.xml"));
        //驼峰命名
        factoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        //輸出日志
        factoryBean.getObject().getConfiguration().setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);
        return factoryBean.getObject();
    }

    @Primary
    @Bean(name = "mysqlTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("mysqlDataSource1") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "mysqlSqlSessionTemplate1")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(
            @Qualifier("sqlSessionFactory1") SqlSessionFactory sqlSessionFactory1) {
        return new SqlSessionTemplate(sqlSessionFactory1);
    }
}

2、数据源二:MysqlDataSource2Config



import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
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.orm.mysql2.mapper", sqlSessionFactoryRef = "sqlSessionFactory2")
public class MysqlDataSource2Config {

    @Bean(name = "mysqlDataSource2")
    @ConfigurationProperties(prefix = "spring.datasource.mysql.v1")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "sqlSessionFactory2")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("mysqlDataSource2") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/mysql2/*Mapper.xml"));
        //驼峰命名
        factoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        //輸出日志
        factoryBean.getObject().getConfiguration().setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);
        return factoryBean.getObject();
    }


    @Bean(name = "mysqlTransactionManager2")
    public DataSourceTransactionManager transactionManager(@Qualifier("mysqlDataSource2") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "mysqlSqlSessionTemplate2")
    public SqlSessionTemplate testSqlSessionTemplate(
            @Qualifier("sqlSessionFactory2") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

3、数据源三:MysqlDataSource3Config



import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
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.orm.mysql3.mapper", sqlSessionFactoryRef = "sqlSessionFactory3")
public class MysqlDataSource3Config {

    @Bean(name = "mysqlDataSource3")
    @ConfigurationProperties(prefix = "spring.datasource.mysql.v2")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "sqlSessionFactory3")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("mysqlDataSource3") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/mysql3/*Mapper.xml"));
        //驼峰命名
        factoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        //輸出日志
        factoryBean.getObject().getConfiguration().setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);
        return factoryBean.getObject();
    }


    @Bean(name = "mysqlTransactionManager3")
    public DataSourceTransactionManager transactionManager(@Qualifier("mysqlDataSource3") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "mysqlSqlSessionTemplate3")
    public SqlSessionTemplate testSqlSessionTemplate(
            @Qualifier("sqlSessionFactory3") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

四、MybatisPlusGeneratorTest根据数据表生成实体类、mapper、xml

代码里面有详细的注解,可自行配置,配置完成后直接运行即可。


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;


public class MybatisPlusGeneratorTest {

    public static void main(String[] args) {

        AutoGenerator autoGenerator = new AutoGenerator();

        //全局配置
        GlobalConfig gc = new GlobalConfig();
        String oPath = System.getProperty("user.dir");//得到当前项目的路径
        gc.setOutputDir(oPath + "/multiple-data-sources/src/main/java/");   //生成文件输出根目录
        gc.setOpen(false);//生成完成后不弹出文件框
        gc.setFileOverride(true);  //文件覆盖
        gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setSwagger2(true); //实体属性 Swagger2 注解

        // 自定义文件命名,注意 %s 会自动填充表实体属性!
        gc.setControllerName("%sController");
        gc.setServiceName("%sApi");
        gc.setServiceImplName("%sService");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        autoGenerator.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);   //设置数据库类型
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        dsc.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8");  //指定数据库
        autoGenerator.setDataSource(dsc);


        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);      // 表名生成策略

        strategy.setInclude(new String[]{"ht_student"});     // 需要生成的表

        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);

        autoGenerator.setStrategy(strategy);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.example.generate");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setMapper("mapper");
        pc.setEntity("entity");
        pc.setXml("xml");
        autoGenerator.setPackageInfo(pc);

        // 执行生成
        autoGenerator.execute();

    }

}


五、实体类entity

因为表都一样,这里拿一个实体类举例,其他复制即可。


import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.io.Serializable;

@Data
@TableName(value = "ht_student")
public class HtStudentV1 implements Serializable {

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private String name;

    private Integer age;

}  


六、mapper层

也拿一个举例,其他复制即可。



import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.orm.mysql1.entity.HtStudentV1;

public interface HtStudentV1Mapper extends BaseMapper<HtStudentV1> {

}



七、dao/service层

是对CURD的扩展


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.orm.mysql1.entity.HtStudentV1;
import com.example.orm.mysql1.mapper.HtStudentV1Mapper;
import org.springframework.stereotype.Service;


@Service
public class HtStudentV1Service extends ServiceImpl<HtStudentV1Mapper, HtStudentV1> {

}


八、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.orm.mysql1.mapper.HtStudentV1Mapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.example.orm.mysql1.entity.HtStudentV1">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="age" property="age"/>
    </resultMap>

</mapper>


九、接口层

import com.alibaba.fastjson.JSONObject;
import com.example.common.Response;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/multiple")
public interface TestMultipleDataSourcesApi {

    @GetMapping(path = "/test")
    Response<JSONObject> test();

}

十、业务层

import com.alibaba.fastjson.JSONObject;
import com.example.api.TestMultipleDataSourcesApi;
import com.example.common.Response;
import com.example.orm.mysql1.dao.HtStudentV1Service;
import com.example.orm.mysql1.entity.HtStudentV1;
import com.example.orm.mysql2.dao.HtStudentV2Service;
import com.example.orm.mysql2.entity.HtStudentV2;
import com.example.orm.mysql3.dao.HtStudentV3Service;
import com.example.orm.mysql3.entity.HtStudentV3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class TestMultipleDataSourcesService implements TestMultipleDataSourcesApi {

    @Autowired
    private HtStudentV1Service htStudentV1Service;

    @Autowired
    private HtStudentV2Service htStudentV2Service;

    @Autowired
    private HtStudentV3Service htStudentV3Service;

    @Override
    public Response<JSONObject> test() {

        Random rand = new Random();

        HtStudentV1 htStudentV1 = new HtStudentV1();
        htStudentV1.setName("小明" + rand.nextInt(100));
        htStudentV1.setAge(rand.nextInt(30));

        HtStudentV2 htStudentV2 = new HtStudentV2();
        htStudentV2.setName("小明" + rand.nextInt(100));
        htStudentV2.setAge(rand.nextInt(30));

        HtStudentV3 htStudentV3 = new HtStudentV3();
        htStudentV3.setName("小明" + rand.nextInt(100));
        htStudentV3.setAge(rand.nextInt(30));

        htStudentV1Service.getBaseMapper().insert(htStudentV1);
        htStudentV2Service.getBaseMapper().insert(htStudentV2);
        htStudentV3Service.getBaseMapper().insert(htStudentV3);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("htStudentV1", htStudentV1Service.list());
        jsonObject.put("htStudentV2", htStudentV2Service.list());
        jsonObject.put("htStudentV3", htStudentV3Service.list());
        return Response.ok(jsonObject);
    }


}

十一、Response返回体


import lombok.Data;

import java.io.Serializable;

@Data
public class Response<T> implements Serializable {

    private static final long serialVersionUID = 1L;
    protected T data;
    protected int code;
    protected String message;

    public Response() {
    }

    public Response(T data) {
        this.data = data;
    }

    public Response(T data, int code, String message) {
        this.data = data;
        this.code = code;
        this.message = message;
    }

    public static <T> Response<T> ok(T data) {
        return new Response(data, 200, "成功");
    }
}


十二、启动项目并测试

地址栏输入:http://localhost:8080/multiple/test
每调用一次,就会在三个库的三个表中插入一条数据

返回结果如下:


{
	"data": {
		"htStudentV1": [{
			"id": 1,
			"name": "39.68371366230235姓名",
			"age": 10
		}, {
			"id": 2,
			"name": "小明90",
			"age": 24
		}],
		"htStudentV2": [{
			"id": 1,
			"name": "29.84551559999581姓名",
			"age": 10
		}, {
			"id": 2,
			"name": "小明24",
			"age": 24
		}],
		"htStudentV3": [{
			"id": 1,
			"name": "66.13283505246086姓名",
			"age": 10
		}, {
			"id": 2,
			"name": "小明63",
			"age": 23
		}]
	},
	"code": 200,
	"message": "成功"
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值