Java教程

springboot整合mybatis设置多数据源的简单使用

本文主要是介绍springboot整合mybatis设置多数据源的简单使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

 设置数据库信息

#主数据源
spring.datasource.primary.url=jdbc:mysql://127.0.0.1:3306/yourheart?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.primary.username=test001
spring.datasource.primary.password=test001
spring.datasource.primary.driverClassName=com.mysql.jdbc.Driver

#副数据源
spring.datasource.second.url=jdbc:mysql://127.0.0.1:3306/yourheart-test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.second.username=test002
spring.datasource.second.password=test002
spring.datasource.second.driverClassName=com.mysql.jdbc.Driver

  设置pom依赖

<!--springboot整合mybatis-->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.2</version>
		</dependency>

		<!--mysql驱动-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.6</version>
		</dependency> 

配置主数据源

package com.java.config;


import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
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.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;

/**
 * @author yourheart
 * @Description
 * @create 2022-05-02 11:52
 */
@Configuration
@MapperScan(basePackages = "com.java.mapper.zero", sqlSessionFactoryRef = "PrimarySqlSessionFactory")//basePackages:接口文件的包路径
public class DruidConfiguration {

    @Value("${spring.datasource.primary.driverClassName}")
    private String driverClassName;

    @Value("${spring.datasource.primary.url}")
    private String url;


    @Value("${spring.datasource.primary.username}")
    private String userName;

    @Value("${spring.datasource.primary.password}")
    private String password;

    @Bean(name = "PrimaryDataSource")
    // 表示这个数据源是默认数据源
    @Primary//这个一定要加,如果两个数据源都没有@Primary会报错
    public DataSource getPrimaryDateSource() {

        HikariConfig config = new HikariConfig();
        config.setDriverClassName(driverClassName);
        config.setJdbcUrl(url);
        config.setUsername(userName);
        config.setPassword(password);
        HikariDataSource dataSource = new HikariDataSource(config);
        return dataSource;

    }


    @Bean(name = "PrimarySqlSessionFactory")
    @Primary
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("PrimaryDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        /**
         * 设置mybatis的xml所在位置
         */
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/zero/*.xml"));
        /**
         * 设置驼峰命名
         */
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }

    @Bean("PrimarySqlSessionTemplate")
    /**
     * 表示这个数据源是默认数据源
     */
    @Primary
    public SqlSessionTemplate primarySqlSessionTemplate(
            @Qualifier("PrimarySqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }





}

  配置从数据库信息

package com.java.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
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.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author yourheart
 * @Description
 * @create 2022-05-02 21:32
 */
@Configuration
@MapperScan(basePackages = "com.java.mapper.first",sqlSessionFactoryRef = "SecondarySqlSessionFactory")
public class SecondaryDataSourceConfig {

    @Value("${spring.datasource.second.driverClassName}")
    private String driverClassName;

    @Value("${spring.datasource.second.url}")
    private String url;


    @Value("${spring.datasource.second.username}")
    private String userName;

    @Value("${spring.datasource.second.password}")
    private String password;

    @Bean(name = "SecondaryDataSource")
    public DataSource getSecondaryDataSource() {
        HikariConfig config = new HikariConfig();
        config.setDriverClassName(driverClassName);
        config.setJdbcUrl(url);
        config.setUsername(userName);
        config.setPassword(password);
        HikariDataSource dataSource = new HikariDataSource(config);
        return dataSource;

    }


    @Bean(name = "SecondarySqlSessionFactory")
    public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("SecondaryDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        /**
         * 设置mybatis的xml所在位置
         */
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/first/*.xml"));

        /**
         * 设置驼峰命名
         */
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }
    @Bean("SecondarySqlSessionTemplate")
    public SqlSessionTemplate secondarySqlSessionTemplate(
            @Qualifier("SecondarySqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }

}

  

 

 

在DruidConfiguration中的basePackages = "com.java.mapper.zero"

表示的意思是会扫描com.java.mapper.zero目录下所有的文件,所以主数据库mapper文件和从数据库mapper文件,最好配置的是同一目录下的两个不同的文件夹

结果就是不然调用那个mapper下的文件,查询的数据都只会是主数据库的数据

 

这篇关于springboot整合mybatis设置多数据源的简单使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!