记录一次SpringBoot+MyBatis-Plus+druid配置多数据源

发布于 2021-07-05  767 次阅读


中途遇到太多坑了,特意记录一下,最开始使用的是mybatis的配置,结果报错,后来又在网上摸索,一直不行,最后根据报错结合了几个配置,发现可以使用多数据源了。

首先配置application.yml文件

spring:
    db1: # 数据源1配置
      url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
      username: root
      password: dancun123456
      driver-class-name: com.mysql.cj.jdbc.Driver
    db2: # 数据源2配置
      url: jdbc:mysql://localhost:3306/db2?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
      username: root
      password: dancun123456
      driver-class-name: com.mysql.cj.jdbc.Driver
    durid:
      initial-size: 1
      max-active: 20
      min-idle: 1
      max-wait: 60000
  autoconfigure:
    exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure # 去除druid配置

特别注意,默认是自动装配数据源,所以我们要排除数据源的自动装配

autoconfigure:<br>    exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure # 去除druid配置<br>

或者在启动类上面排除自动装配

@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)

下面是配置类

package com.example.demo.configuration;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringBootConfiguration;
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;

/**
 * @ClassName: MyBatisPlusConfig
 * @Description: MyBatisPlus配置类
 * @Author: dancun
 * @Date: 2021-7-4 - 23:49
 */
@Configuration
@MapperScan(basePackages = "com.example.demo.mapper.db1", sqlSessionFactoryRef = "primarySqlSessionFactory", sqlSessionTemplateRef = "primarySqlSessionTemplate")
@MapperScan(basePackages = "com.example.demo.mapper.db2", sqlSessionFactoryRef = "secondSqlSessionFactory", sqlSessionTemplateRef = "secondSqlSessionTemplate")
public class MyBatisPlusConfig
{
    /**
     * 主数据源
     */
    @Primary
    @Bean(name = "primaryDataSource")
    @ConfigurationProperties("spring.datasource.db1")
    public DataSource primaryDataSource()
    {
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 次数据源
     */
    @Bean(name = "secondDataSource")
    @ConfigurationProperties("spring.datasource.db2")
    public DataSource secondDataSource()
    {
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 主会话工厂
     */
    @Bean("primarySqlSessionFactory")
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception
    {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
//        sqlSessionFactoryBean.setTypeAliasesPackage("com.xxxx.bean.domain");
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        sqlSessionFactoryBean.setConfiguration(configuration);
//        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/xxxx/mapper/primary/*.xml"));
        sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * 次会话工厂
     */
    @Bean("secondSqlSessionFactory")
    public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception
    {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
//        sqlSessionFactoryBean.setTypeAliasesPackage("com.xxxx.bean.domain");
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        sqlSessionFactoryBean.setConfiguration(configuration);
//        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/xxxx/mapper/second/*.xml"));
        sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * 主会话模板
     */
    @Bean("primarySqlSessionTemplate")
    public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory)
    {
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
        return sqlSessionTemplate;
    }

    /**
     * 次会话模板
     */
    @Bean("secondSqlSessionTemplate")
    public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory)
    {
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
        return sqlSessionTemplate;
    }

    /**
     * 分页插件
     */
    @Bean
    public PaginationInnerInterceptor paginationInnerInterceptor()
    {
        return new PaginationInnerInterceptor();
    }
}

这是主配属文件,其中BasePackages是扫描包路径,会将配置的手动配置了数据源的sqlSessionFactory和sqlSessionTemplate注入到mapper当中。

@MapperScan(basePackages = "com.example.demo.mapper.db1", sqlSessionFactoryRef = "primarySqlSessionFactory", sqlSessionTemplateRef = "primarySqlSessionTemplate")