Springboot整合Mybatis多数据源配置

话不多说,直接进入正题。源码地址:https://github.com/SuriYesl/template.git

目录

一、数据库配置文件

二、配置类

主数据源配置类:

次数据源配置类:

三、项目结构(重点是mapper结构和配置类里的路径对应)

四、启动类——启动类需要取消加载数据源自动配置

五、测试:

controller:

Service:

Mapper:

数据库数据:

postman调用接口结果:


一、数据库配置文件

spring:
  datasource:
    test1:
        jdbc-url: jdbc:mysql://localhost:3306/alice_test?serverTimezone=CTT&useUnicode=true&characterEncoding=utf8
        driverClassName: com.mysql.cj.jdbc.Driver
        username: root
        password: xxx
    test2:
        jdbc-url: jdbc:mysql://localhost:3306/alice_test_two?serverTimezone=CTT&useUnicode=true&characterEncoding=utf8
        driverClassName: com.mysql.cj.jdbc.Driver
        username: root
        password: xxx

mybatis:
  mapper-locations: classpath:*/mapper/**.xml

注意事项:url修改为jdbc-url,在单数据源配置中,使用的是url,不是jdbc-url。多数据源配置中使用url启动会报错,具体出错信息参考上一篇文章springboot+mybatis多数据源错误信息

二、配置类

主数据源配置类:

package com.alice.springboot.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 javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.alice.springboot.mapper.test", sqlSessionFactoryRef = "test1SqlSessionFactory")
public class DataSourceConfig1 {

    // 将这个对象放入Spring容器中
    @Bean(name = "test1DataSource")
    // 表示这个数据源是默认数据源
    @Primary
    // 读取application.properties中的配置参数映射成为一个对象
    // prefix表示参数的前缀
    @ConfigurationProperties(prefix = "spring.datasource.test1")
    public DataSource getDateSource1()
    {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "test1SqlSessionFactory")
    // 表示这个数据源是默认数据源
    @Primary
    // @Qualifier表示查找Spring容器中名字为test1DataSource的对象
    public SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1DataSource") DataSource datasource)
            throws Exception
    {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/test/*.xml"));
        return bean.getObject();
    }

    @Bean("test1SqlSessionTemplate")
    // 表示这个数据源是默认数据源
    @Primary
    public SqlSessionTemplate test1SqlSessionTemplate(
            @Qualifier("test1SqlSessionFactory") SqlSessionFactory sessionFactory)
    {
        return new SqlSessionTemplate(sessionFactory);
    }
}

次数据源配置类:

package com.alice.springboot.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 javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.alice.springboot.mapper.testTwo", sqlSessionFactoryRef = "test2SqlSessionFactory")
public class DataSourceConfig2 {
    @Bean(name = "test2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test2")
    public DataSource getDateSource2()
    {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "test2SqlSessionFactory")
    public SqlSessionFactory test2SqlSessionFactory(@Qualifier("test2DataSource") DataSource datasource)
            throws Exception
    {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/testTwo/*.xml"));
        return bean.getObject();
    }

    @Bean("test2SqlSessionTemplate")
    public SqlSessionTemplate test2SqlSessionTemplate(
            @Qualifier("test2SqlSessionFactory") SqlSessionFactory sessionFactory)
    {
        return new SqlSessionTemplate(sessionFactory);
    }
}

三、项目结构(重点是mapper结构和配置类里的路径对应)

四、启动类——启动类需要取消加载数据源自动配置

因为Springboot的强大的自动配置,让我们省去了很多功夫,但同时,如果你不需要使用自动配置,那么需要取消加载对应的自动配置类。

package com.alice.springboot;

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

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
//@MapperScan("com.alice.springboot.mapper.*")
public class AliceApplication {

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

}

五、测试:

controller:

package com.alice.springboot.controller;

import com.alice.springboot.constants.ResponseStatusEnum;
import com.alice.springboot.entity.FieldEntity;
import com.alice.springboot.model.ResponseResult;
import com.alice.springboot.service.ITableHeaderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 表头信息接口
 */
@RequestMapping(value = "/alice/tableHeader")
@RestController
public class TableHeaderController {
    @Autowired
    private ITableHeaderService tableHeaderService;

    @RequestMapping(value = "/tableHeaderInfos", method = RequestMethod.GET)
    public ResponseResult<List<FieldEntity>> getTableHeaderFields(String category)
    {
        ResponseResult<List<FieldEntity>> result = new ResponseResult<>();

        try {
            result.setData(tableHeaderService.getTableFieldByCategory(category));
            result.setCode("200");
            result.setMessage("查询" + category + "表头信息成功");
            result.setStatus(ResponseStatusEnum.SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @RequestMapping(value = "/tableHeaderTwoInfos", method = RequestMethod.GET)
    public ResponseResult<List<FieldEntity>> getTableHeaderTwoFields(String category)
    {
        ResponseResult<List<FieldEntity>> result = new ResponseResult<>();

        try {
            result.setData(tableHeaderService.getTableFieldByCategoryWithTwoDataBase(category));
            result.setCode("200");
            result.setMessage("查询" + category + "表头信息成功");
            result.setStatus(ResponseStatusEnum.SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}

Service:

package com.alice.springboot.service.impl;

import com.alice.springboot.entity.FieldEntity;
import com.alice.springboot.mapper.test.TableHeaderMapper;
import com.alice.springboot.mapper.testTwo.TableHeaderTwoMapper;
import com.alice.springboot.model.MultiLevelHeaderVO;
import com.alice.springboot.service.ITableHeaderService;
import com.alice.springboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.List;

/**
 * 表头信息服务实现
 */
@Service
public class TableHeaderServiceImpl implements ITableHeaderService {
    @Autowired
    private TableHeaderMapper tableHeaderMapper;

    @Autowired
    private TableHeaderTwoMapper tableHeaderTwoMapper;

    @Override
    public List<FieldEntity> getTableFieldByCategory(String category) {
        return tableHeaderMapper.getTableHeaderFieldByCategory(category);
    }


    @Override
    public List<FieldEntity> getTableFieldByCategoryWithTwoDataBase(String category) {
        return tableHeaderTwoMapper.getTableHeaderFieldByCategory(category);
    }
}

Mapper:

test1包下:

package com.alice.springboot.mapper.test;

import com.alice.springboot.entity.FieldEntity;

import java.util.List;

/**
 * 表头信息mapper
 */
public interface TableHeaderMapper {
    /**
     * 根据模块获取表头信息
     * @param category 模块
     * @return 表头信息
     */
    List<FieldEntity> getTableHeaderFieldByCategory(String category);

    /**
     * 根据模块获取Excel表头信息
     * @param category 模块
     * @return 表头信息
     */
    List<FieldEntity> getExcelHeaderFieldByCategory(String category);
}

test1包下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.alice.springboot.mapper.test.TableHeaderMapper">

    <select id="getTableHeaderFieldByCategory" resultType="com.alice.springboot.entity.FieldEntity">
        select * from alice_table_header where category = #{param1} order by labelIndex;
    </select>

    <select id="getExcelHeaderFieldByCategory" resultType="com.alice.springboot.entity.FieldEntity">
        select * from alice_table_header where isExportField = 1 and category = #{param1} order by exportIndex;
    </select>
</mapper>

test2包下:

package com.alice.springboot.mapper.testTwo;

import com.alice.springboot.entity.FieldEntity;

import java.util.List;

/**
 * 表头信息mapper
 */
public interface TableHeaderTwoMapper {
    /**
     * 根据模块获取表头信息
     * @param category 模块
     * @return 表头信息
     */
    List<FieldEntity> getTableHeaderFieldByCategory(String category);

    /**
     * 根据模块获取Excel表头信息
     * @param category 模块
     * @return 表头信息
     */
    List<FieldEntity> getExcelHeaderFieldByCategory(String category);
}

test2包下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.alice.springboot.mapper.testTwo.TableHeaderTwoMapper">

    <select id="getTableHeaderFieldByCategory" resultType="com.alice.springboot.entity.FieldEntity">
        select * from alice_table_header where category = #{param1} order by labelIndex;
    </select>

    <select id="getExcelHeaderFieldByCategory" resultType="com.alice.springboot.entity.FieldEntity">
        select * from alice_table_header where isExportField = 1 and category = #{param1} order by exportIndex;
    </select>
</mapper>

数据库数据:

postman调用接口结果:

调用test1数据源:

调用test2数据源:

评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值