tk-mybatis整合springBoot使用兩個數據源的方法

根據項目功能需求,需要與第三方公共庫對接,需要對公共庫進行相關操作,由於不想使用原生jdbc,所以采用mybaits進行多數據配置。

單純的使用mybaits進行多數據配置網上資料很多,但由於前期為瞭方便開發,采用瞭tk-mybaits。關於tk-mybaits多數據源配置沒有相關材料,官方也沒有提供相關功能說明,所以最終采用mybatis+tk-mybaits分別使用的策略進行多數據源配置功能實現。具體代碼如下

一、配置連接信息

#開發運行環境數據庫
spring.datasource.local.url=jdbc:mysql://0.0.0.0:3306/zhdd
spring.datasource.local.username=root
spring.datasource.local.password=
spring.datasource.local.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.local.druid.initial-size=1
spring.datasource.local.druid.min-idle=1
spring.datasource.local.druid.max-active=20
spring.datasource.local.druid.test-on-borrow=true
spring.datasource.local.druid.stat-view-servlet.allow=true
 
#第三方對接通用數據庫
spring.datasource.public.url=jdbc:mysql://0.0.0.0:3306/zhdd
spring.datasource.public.username=root
spring.datasource.public.password=
spring.datasource.public.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.public.druid.initial-size=1
spring.datasource.public.druid.min-idle=1
spring.datasource.public.druid.max-active=20
spring.datasource.public.druid.test-on-borrow=true
spring.datasource.public.druid.stat-view-servlet.allow=true

 二、配置DataSource數據源

 註意兩個數據源中有一個是為主數據源,需要增加一個@Primary註解,有且隻能有一個需要。關於2個以上數據源沒有額外再進行研究瞭,不過利用mybatis再額外配置多個數據源應該可以實現

1.數據源1配置

package com.hiynn.core.mybatis;
 
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
 
import javax.sql.DataSource;
 
/**
 * 開發運行環境數據庫
 */
@Configuration
public class LocalDataSourceConfig {
 
    @Bean(name = "localDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.local")
    @Primary
    public DataSource localDataSource() {
        return DruidDataSourceBuilder.create().build();
    }
 
    @Bean(name = "localTransactionManager")
    @Primary
    public DataSourceTransactionManager mysqlTransactionManager() {
        return new DataSourceTransactionManager(localDataSource());
    }
 
    @Bean(name = "localSqlSessionFactory")
    @Primary
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("localDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        //如果不使用xml的方式配置mapper,則可以省去下面這行mapper location的配置。
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mapper/*.xml"));
        return sessionFactory.getObject();
    }
}

2.數據源2配置

package com.hiynn.core.mybatis;
 
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
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
public class PublicDataSourceConfig {
 
    @Bean(name = "publicDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.public")
    public DataSource publicDataSource() {
        return DruidDataSourceBuilder.create().build();
    }
 
    @Bean(name = "publicTransactionManager")
    public DataSourceTransactionManager mysqlTransactionManager() {
        return new DataSourceTransactionManager(publicDataSource());
    }
 
    @Bean(name = "publicSqlSessionFactory")
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("publicDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        //如果不使用xml的方式配置mapper,則可以省去下面這行mapper location的配置。
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mapper2/*.xml"));
        return sessionFactory.getObject();
    }
}

三、Application配置

package com.hiynn.core;
 
//特別註意,下面的是 tk.MapperScan
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import tk.mybatis.spring.annotation.MapperScan;
 
/**
 * @author zz
 * @date 2018-7-2
 */
@ServletComponentScan
@SpringBootApplication
@EnableTransactionManagement
@EnableSwagger2
@MapperScan(basePackages = "com.hiynn.core.**.mapper",sqlSessionFactoryRef = "localSqlSessionFactory")
@org.mybatis.spring.annotation.MapperScan(basePackages = "com.hiynn.core.**.mapper2",sqlSessionFactoryRef = "publicSqlSessionFactory")
public class Application extends SpringBootServletInitializer{
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

四、Mapper代碼結構

補充:

一、解決mybatis數據庫駝峰命名自動映射問題以及sql語句打印問題,通過讀取配置文件實現。兩個數據源都需要設置

    @Bean(name = "localSqlSessionFactory")
    @Primary
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("localDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        //添加mybatis配置文件讀取功能更
        sessionFactory.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("mybatis-config.xml"));
        //如果不使用xml的方式配置mapper,則可以省去下面這行mapper location的配置。
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mapper/*.xml"));
        return sessionFactory.getObject();
    }
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true" />
        <!-- 打印查詢語句 -->
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
</configuration>

二、配置PageHelper分頁插件,在application.properties統一配置

數據庫方言 指定分頁插件使用哪種數據庫方言
pagehelper.helperDialect=mysql
#分頁參數合理化 pageNum<=0 時會查詢第一頁, pageNum>pages(超過總數時),會查詢最後一頁
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

到此這篇關於tk-mybatis整合springBoot使用兩個數據源的方法的文章就介紹到這瞭,更多相關tk-mybatis springBoot數據源內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: