小白起步之SpringBoot+Mybatis多数据源配置

  1. pom文件
<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.3.RELEASE</version>
		<relativePath/>
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<!-- alibaba的druid数据库连接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.0</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>
#application.properties中配置数据库
数据源1
spring.datasource.primary.jdbcUrl=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimeZone=Asia
spring.datasource.primary.username=root
spring.datasource.primary.password=root
spring.datasource.primary.driverClassName=com.mysql.jdbc.Driver
#数据源2
spring.datasource.slave.jdbcUrl=jdbc:mysql://localhost:3306/ybk?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimeZone=Asia
spring.datasource.slave.username=root
spring.datasource.slave.password=root
spring.datasource.slave.driverClassName=com.mysql.jdbc.Driver
  1. 代码结构
    在这里插入图片描述

  2. 配置文件代码

package com.example.demo.config;
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 javax.sql.DataSource;
@Configuration
public class DataSourceConfig {
    @Primary
    @Bean(name = "primaryDataSource")
    //指定数据读取配置的前缀
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource(){
        return DataSourceBuilder.create().build() ;
    }

    @Bean(name = "slaveDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDataSource(){
        return DataSourceBuilder.create().build() ;
    }
}
package com.example.demo.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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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;

/**
 * 数据源primary
 */
@Configuration
@MapperScan(basePackages = {"com.example.demo.mapper.primary"}, sqlSessionFactoryRef = "sqlSessionFactoryPrimary")
public class MybatisPrimaryConfig {
    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource ;
    @Bean
    @Primary
    public SqlSessionFactory sqlSessionFactoryPrimary() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean() ;
        factoryBean.setDataSource(primaryDataSource);//设置数据源
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:primaryMybatis/*Mapper.xml"));
        return factoryBean.getObject() ;
    }
    @Bean
    public SqlSessionTemplate sqlSessionTemplatePrimary() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactoryPrimary()) ;
        return template ;
    }
}
package com.example.demo.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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 数据源二
 */
@Configuration
//指定basePackages下的mapper使用当前数据源
@MapperScan(basePackages = {"com.example.demo.mapper.slave"}, sqlSessionFactoryRef = "sqlSessionFactorySlave")
public class MybatisSlaveConfig {
    @Autowired
    @Qualifier("slaveDataSource")
    private DataSource slaveDataSource ;
    @Bean
    public SqlSessionFactory sqlSessionFactorySlave() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean() ;
        factoryBean.setDataSource(slaveDataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(
                "classpath*:slaveMybatis/*Mapper.xml"));
        return factoryBean.getObject() ;
    }
    @Bean
    public SqlSessionTemplate sqlSessionTemplateSlave() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactorySlave()) ;
        return template ;
    }
}
  1. 测试数据源一
package com.example.demo.mapper.primary;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserPrimaryMapper {
    @Select("SELECT addr FROM info WHERE id=1;;")
    String queryOne( );
}

  1. 测试数据源二
package com.example.demo.mapper.slave;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserSlaveMapper {
    @Select("SELECT name FROM account WHERE id=1001;")
    String queryAcc();
}
  1. 整合mapper的service
package com.example.demo.service;

import java.util.Map;
public interface TestService {
    public Map<String,Object> testMysql();
}

package com.example.demo.service.impl;

import com.example.demo.mapper.primary.UserPrimaryMapper;
import com.example.demo.mapper.slave.UserSlaveMapper;
import com.example.demo.service.TestService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
@Service
public class TestServiceImpl implements TestService {
    @Resource
    private UserPrimaryMapper userPrimaryMapper;
    @Resource
    private UserSlaveMapper userSlaveMapper;
    public Map<String,Object> testMysql() {
        String queryOne = userPrimaryMapper.queryOne();
        String queryAcc = userSlaveMapper.queryAcc();
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("primary",queryOne);
        map.put("slave",queryAcc);
        return map;
    }
}

  1. 测试service的test类
package com.example.demo;

import com.example.demo.service.TestService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ServiceTest {
    @Resource
    private TestService testService;
    @Test
    public void testMysqlT(){
        Map<String,Object> map = testService.testMysql();
        System.out.println("<<<<<<<<<<<<<<<<<<<<<<<"+map+">>>>>>>>>>>>>>>>>>>>>>>>>");
        Assert.assertNotNull(map);
    }
}

  1. 运行结果
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值