springboot mybatis多数据源

原创
2019/08/05 10:24
阅读数 115

需求

项目有一个需求,需要从多数据源读取数据。因此使用springboot+mybatis进行多数据源配置和操作。

依赖引入

        <!-- mybatis db -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>

配置文件

# ds1数据源配置
spring.datasource.ds1.url=jdbc:mysql://ip1:port/database?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.ds1.username=xxxxxx
spring.datasource.ds1.password=xxxxxx
spring.datasource.ds1.driver-class-name=com.mysql.cj.jdbc.Driver

# ds2数据源配置
spring.datasource.ds2.url=jdbc:mysql://ip2:port/database?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.ds2.username=xxxxxx
spring.datasource.ds2.password=xxxxxx
spring.datasource.ds2.driver-class-name=com.mysql.cj.jdbc.Driver

# ds3数据源配置
spring.datasource.ds3.url=jdbc:mysql://ip3:port/database?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.ds3.username=xxxxxx
spring.datasource.ds3.password=xxxxxx
spring.datasource.ds3.driver-class-name=com.mysql.cj.jdbc.Driver

Java配置

package com.qishu.demo.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
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.qishu.demo.ds1.dao", sqlSessionFactoryRef = "ds1SqlSessionFactory")
public class Ds1DatasourceConfig {

    @Primary
    @Bean(name = "ds1DataSource")
    @ConfigurationProperties("spring.datasource.ds1")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "ds1SqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("ds1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:ds1-mapper/*.xml"));
        return sessionFactoryBean.getObject();
    }
}
package com.qishu.demo.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
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.qishu.demo.ds2.dao", sqlSessionFactoryRef = "ds2SqlSessionFactory")
public class Ds2DatasourceConfig {

    @Bean(name = "ds2DataSource")
    // 配置前缀
    @ConfigurationProperties("spring.datasource.ds2")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "ds2SqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("ds2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        // mapper文件目录
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:ds2-mapper/*.xml"));
        return sessionFactoryBean.getObject();
    }
}

ds3就不写了

使用方式

    @Autowired
    private AppDAO appDAO;

修改启动类

// 排除自动注册配置
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, MybatisAutoConfiguration.class})

单元测试

// EnableAutoConfiguration注解,关闭springBoot关于mybatis的一些自动注入。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, MybatisAutoConfiguration.class})
public class AppDAOTest {

    @Autowired
    private AppDAO appDAO;


    @Test
    public void selectTest() {
        AppDO appDO = appDAO.selectByPrimaryKey(70);
        System.out.println(JSON.toJSONString(appDO));
    }
}

目录结构

问题汇总

在ds1中使用 @Primary 对SqlSessionFactory和DataSource的Bean进行指定,否则会报

NoUniqueBeanDefinitionException: No qualifying bean of type SqlSessionFactory

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部