Springboot整合Mybatis多數據源配置

話不多說,直接進入正題。源碼地址:https://github.com/AliceAsuna/KiritoV1.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*:mapping/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數據源:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章