SpringBoot+mybatis配置双数据源配置案例

任务要求

公司某项目需要配置双数据源来调用 sql server 数据库存过,处理存过返回数据并将结果返回到前台页面。

案例实现

因为要调用的是 sql server ,因此我们需要引入对应的驱动依赖。

pom.xml

      <!--sqlserver依赖  驱动jar-->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
            <version>6.4.0.jre8</version>
        </dependency>
	<!-- 注意 目前mvn库上暂时只有4.0版本 -->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>sqljdbc4</artifactId>
            <version>4.0</version>
        </dependency>

yaml配置

spring:
  application:
    name: spring-boot
  datasource:
    oracle:
      type: org.apache.tomcat.jdbc.pool.DataSource #tomcat连接池,支持druid dbcp dbcp2
      driver-class-name: oracle.jdbc.driver.OracleDriver
      username: username
      password: password 
      url: jdbc:oracle:xxxxxxxxx
    sqlserver:
      type: javax.sql.DataSource
      driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
      username: username
      password: 'test@test:' # 密码有特殊符号时,用单引号即可
      url: jdbc:sqlserver://xxxxxxx

## mapper配置
mybatis:
  mapper-locations: classpath:com/x/xx/*/*/mapper/*.xml      

oracle数据源配置文件

package com.x.xx.xxx.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.autoconfigure.jdbc.DataSourceBuilder;
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.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * oracle 数据库配置文件
 * @author : Duan
 */
@Configuration
@MapperScan(basePackages = "com.x.xx.xxx.*.mapper", sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class OracleDataSourceConfig {
    /**
     * 生成数据源.  @Primary 注解声明为默认数据源
     */
    @Bean(name = "db1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.oracle")
    @Primary
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 创建 SqlSessionFactory
     */
    @Bean(name = "db1SqlSessionFactory")
    @Primary
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    /**
     * 配置事务管理
     */
    @Bean(name = "db1TransactionManager")
    @Primary
    public DataSourceTransactionManager testTransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "db1SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

sql server数据源配置文件

package com.x.xx.smart.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.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * sql server数据库配置文件
 * @author : Duan
 */
@Configuration
// 这里因为是单一需求,所以暂时只需要精准指定mapper路径即可
@MapperScan(basePackages = "com.x.xx.smart.mapper", sqlSessionTemplateRef = "db2SqlSessionTemplate")
public class SqlServerDataSourceConfig {

    @Bean(name = "db2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.sqlserver")
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "db2SqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    @Bean(name = "db2TransactionManager")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("db2DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "db2SqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

启动文件

import com.x.xx.xxx.common.util.SpringContextUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@EnableScheduling
@ComponentScan("com.x.xx.*") // 因为sql server要和主业务区分开,不能放在xxx包路径下,又懒得动启动类位置了,故而这里需要重新指定一下扫描路径
public class ServiceApplication {

    public static void main(String[] args) {
        ApplicationContext run =SpringApplication.run(ServiceApplication.class, args);
        SpringContextUtil.setApplicationContext(run);
    }

}

附一下调用sql server 存过的写法

<?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.x.xx.smart.mapper.SmartMapper">

    <select id="callProc" resultType="map" parameterType="map" statementType="CALLABLE">
        exec [存过名称] @param=#{param}, @paramSecond=#{paramSecond}
    </select>
</mapper>

最后controller,service等按照逻辑实现即可。

参考文档1


版权声明:本文为yishengdalanrou原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。