springboot 通用mapper双数据源配置

时间:2024-05-31 10:31:49

因为项目需要,项目内使用双数据源。我又很懒,不想写单表的简单SQL,就把通用mapper集成进去了。

通用mapper本身配置我就忽略掉了,重点放出双数据源的配置

1、项目结构

springboot 通用mapper双数据源配置

 

application.properties

spring.profiles.active=dev
corpus.domain=false
server.port=8062
#mybatis.mapperLocations=classpath:mapper/mysql/*.xml
#mybatis.type-aliases-package=com.zhan.corpus.domain
toefl.mybatis.mapperLocations=classpath:mapper/mysql/*.xml
ielts.mybatis.mapperLocations=classpath:mapper/ielts/*.xml

#上传文件的大小限制
spring.http.multipart.maxFileSize=50MB
spring.http.multipart.maxRequestSize=50MB

application-dev.properties


## mysql config
toefl.datasource.driver-class-name = com.mysql.jdbc.Driver
toefl.datasource.url = jdbc:mysql://127.0.0.1:3306/xzdb?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&autoReconnectForPools=true
toefl.datasource.username = root
toefl.datasource.password = pwd
toefl.datasource.commit-on-return=true
toefl.datasource.initialSize=5
toefl.datasource.minIdle=5
toefl.datasource.maxIdle=50
toefl.datasource.maxWait=3000
toefl.datasource.maxActive=50
toefl.datasource.test-on-borrow=true
toefl.datasource.test-while-idle=true
toefl.datasource.validation-query=SELECT 1 FROM DUAL
#空闲连接回收的时间间隔,与test-while-idle一起使用,设置5分钟
toefl.datasource.time-between-eviction-runs-millis=300000
#连接池空闲连接的有效时间 ,设置30分钟
toefl.datasource.min-evictable-idle-time-millis=1800000
#指定多少ms执行一次连接校验
toefl.datasource.validation-interval=300000

ielts.datasource.driver-class-name = com.mysql.jdbc.Driver
ielts.datasource.url=jdbc:mysql://127.0.0.1:3306/ieltsdb?zeroDateTimeBehavior=convertToNull&autoReconnect=true
ielts.datasource.username=name
ielts.datasource.password=pwd
ielts.datasource.commit-on-return=true
ielts.datasource.initialSize=5
ielts.datasource.minIdle=5
ielts.datasource.maxIdle=50
ielts.datasource.maxWait=3000
ielts.datasource.maxActive=50
ielts.datasource.test-on-borrow=true
ielts.datasource.test-while-idle=true
ielts.datasource.validation-query=SELECT 1 FROM DUAL
#空闲连接回收的时间间隔,与test-while-idle一起使用,设置5分钟
ielts.datasource.time-between-eviction-runs-millis=300000
#连接池空闲连接的有效时间 ,设置30分钟
ielts.datasource.min-evictable-idle-time-millis=1800000
#指定多少ms执行一次连接校验
ielts.datasource.validation-interval=300000

ToeflMybatisConfig  主数据源 配置了tkmybatis

package com.zhan.corpus.spring.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

/**
 * 主数据源
 * 注意,要支持tk-mybatis扩展中间件,需要用tk.mybatis.spring.annotation.MapperScan注解
 */
@Configuration
@MapperScan(basePackages = {"com.zhan.corpus.dao.toefl"}, sqlSessionTemplateRef = "userSqlSessionTemplate")
public class ToeflMybatisConfig {
    @Value("${toefl.mybatis.mapperLocations}")
    private String mainMapper;
    @Bean(name = "userDataSource")
    @Primary //必须加此注解,不然报错,下一个类则不需要添加
    @ConfigurationProperties(prefix = "toefl.datasource") //prefix值必须是application.properteis中对应属性的前缀
    public DataSource userDataSource() {
        return DataSourceBuilder.create().build();
    }
    /**
     * 配置事务管理器
     *
     * @param dataSource
     * @return
     */
    @Bean(name = "masterTransactionManger")
    @Primary
    public DataSourceTransactionManager masterTransactionManger(@Qualifier("userDataSource") DataSource dataSource) {
         return new DataSourceTransactionManager(dataSource);
     }
    @Bean
    @Primary
    public SqlSessionFactory userSqlSessionFactory(@Qualifier("userDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setVfs(SpringBootVFS.class);
        bean.setTypeAliasesPackage("com.zhan.corpus.domain.toefl");
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            bean.setMapperLocations(resolver.getResources(mainMapper));
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    @Bean
    @Primary
    public SqlSessionTemplate userSqlSessionTemplate(@Qualifier("userSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
    // 使用上面配置的Factory
        return template;
     }
    @Bean(name = "mainJdbcTemplate")
    public JdbcTemplate mainJdbcTemplate(@Qualifier("userDataSource") DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
}

 

IeltsMybatisConfig

package com.zhan.corpus.spring.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.beans.factory.annotation.Value;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * @author bean.zhang
 */
@Configuration
@MapperScan(basePackages = {"com.zhan.corpus.dao.ielts"}, sqlSessionTemplateRef = "ieltsSqlSessionTemplate")
public class IeltsMybatisConfig {
    @Value("${ielts.mybatis.mapperLocations}")
    private String ieltsMapper;

    /**
     * dataSource配置
     *prefix值必须是application.properteis中对应属性的前缀
     * @return
     */
    @Bean(name = "ieltsDataSource")
    @ConfigurationProperties(prefix = "ielts.datasource")
    public DataSource ylkDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean
    public SqlSessionFactory ieltsSqlSessionFactory(@Qualifier("ieltsDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            //添加XML目录
            bean.setMapperLocations(resolver.getResources(ieltsMapper));
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    @Bean
    public SqlSessionTemplate ieltsSqlSessionTemplate(@Qualifier("ieltsSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        // 使用上面配置的Factory
        return template;
    }
    @Bean(name = "ieltsJdbcTemplate")
    public JdbcTemplate ieltsJdbcTemplate(@Qualifier("ieltsDataSource") DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
}

 

DAO

springboot 通用mapper双数据源配置

 

springboot启动类

springboot 通用mapper双数据源配置