SpringBoot(10):SpringBoot+Mybatis多数据源解决方案

首先是pom.xml

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.springboot</groupId>
	<artifactId>study</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>SpringBoot-MultiDatasource</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.10.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.7</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.scala-lang</groupId>
			<artifactId>scala-library</artifactId>
			<version>2.11.0</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

application.yml

mybatis:
  type-aliases-package: com.springboot.study.entity
  configuration:
    map-underscore-to-camel-case: true

test1: 
  datasource:
    url: jdbc:mysql://localhost:3306/girl 
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver 
     
test2: 
  datasource:
    url: jdbc:mysql://localhost:3306/mkdlp
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

在这个配置文件中首先对Mybatis进行了简单的配置,然后配置了两个数据源的信息,其中test1将会作为主数据源。

下面是数据源配置:

DataSource1Config.java

package com.springboot.study.datasource;

import javax.sql.DataSource;

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.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.jdbc.datasource.DataSourceTransactionManager;


@Configuration
@MapperScan(basePackages="com.springboot.study.mapper.test1",sqlSessionTemplateRef="test1SqlSessionTemplate")
public class DataSource1Config {
	
	@Bean(name="test1DataSource")
	@ConfigurationProperties(prefix="test1.datasource")//按照在application.yml的数据源的前缀
	@Primary//一定要确定主数据源,不然会出问题
	public DataSource testDataSource(){
		return DataSourceBuilder.create().build();
	}
	
	@Bean(name="test1SqlSessionFactory")
	@Primary
	public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource")DataSource dataSource) throws Exception{
		SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		return bean.getObject();
	}
	
	@Bean("test1TransactionManager")
	@Primary
	public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource){
		return new DataSourceTransactionManager(dataSource);
	}
	
	@Bean(name="test1SqlSessionTemplate")
	@Primary
	public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) 
			throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

DataSource2Config.java

package com.springboot.study.datasource;

import javax.sql.DataSource;

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.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.jdbc.datasource.DataSourceTransactionManager;


@Configuration
@MapperScan(basePackages="com.springboot.study.mapper.test2",sqlSessionTemplateRef="test2SqlSessionTemplate")
public class DataSource2Config {
	
	@Bean(name="test2DataSource")
	@ConfigurationProperties(prefix="test2.datasource")
	public DataSource testDataSource(){
		return DataSourceBuilder.create().build();
	}
	
	@Bean(name="test2SqlSessionFactory")
	public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource")DataSource dataSource) throws Exception{
		SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		return bean.getObject();
	}
	
	@Bean("test2TransactionManager")
	public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource){
		return new DataSourceTransactionManager(dataSource);
	}
	
	@Bean(name="test2SqlSessionTemplate")
	public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

上面两个JAVA类分别配置了两个数据源,其中@Primary的是主数据源的注解,一定要记得确定主数据源,不然会出问题。

在这里我们使用注解的方式,下面贴出Mapper

Girl1Mapper.java

package com.springboot.study.mapper.test1;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.springboot.study.entity.Girl;

public interface Girl1Mapper {
	
	
	@Select("select * from girl")
	@Results({
		@Result(property="id",column="id"),
		@Result(property="age",column="age"),
		@Result(property="cupSize",column="cup_size"),
	})
	public List<Girl> findAllGirls();
	
	@Select("select * from girl where id=#{id}")
	@Results({
		@Result(property="id",column="id"),
		@Result(property="age",column="age"),
		@Result(property="cupSize",column="cup_size")
	})
	public Girl findById(Integer id);
	
	@Insert("insert into girl values(#{id},#{age},#{cupSize})")
	public int addGirl(Girl girl);
	
	@Delete("delete from girl where id=#{id}")
	public int deleteGirl(Integer id);
	
	@Update("update girl set age=#{age},cup_size=#{cupSize} where id=#{id}")
	public int updateGirl(Girl girl);
}

Girl2Mapper.java

package com.springboot.study.mapper.test2;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.springboot.study.entity.Girl;

public interface Girl2Mapper {
	
	
	@Select("select * from girl")
	@Results({
		@Result(property="id",column="id"),
		@Result(property="age",column="age"),
		@Result(property="cupSize",column="cup_size"),
	})
	public List<Girl> findAllGirls();
	
	@Select("select * from girl where id=#{id}")
	@Results({
		@Result(property="id",column="id"),
		@Result(property="age",column="age"),
		@Result(property="cupSize",column="cup_size")
	})
	public Girl findById(Integer id);
	
	@Insert("insert into girl values(#{id},#{age},#{cupSize})")
	public int addGirl(Girl girl);
	
	@Delete("delete from girl where id=#{id}")
	public int deleteGirl(Integer id);
	
	@Update("update girl set age=#{age},cup_size=#{cupSize} where id=#{id}")
	public int updateGirl(Girl girl);
}

这样的话就完成了mapper,然后我们新建一个Controller类来测试一下多数据源的方案成功了没

GirlController.java

package com.springboot.study.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.springboot.study.entity.Girl;
import com.springboot.study.mapper.test1.Girl1Mapper;
import com.springboot.study.mapper.test2.Girl2Mapper;

@RestController
public class GirlController {
	
	@Autowired
	Girl1Mapper mapper1;
	
	@Autowired
	Girl2Mapper mapper2;
	
	@RequestMapping("/girls1")
	public List<Girl> getAll1(){
		return mapper1.findAllGirls();
	}
	
	@RequestMapping("/girls2")
	public List<Girl> getAll2(){
		return mapper2.findAllGirls();
	}
	
	@RequestMapping("/girl")
	public Girl findGirls(Integer id){
		return mapper1.findById(id);
	}
	
	@RequestMapping("/addGirl")
	public int addGirl(){
		return mapper1.addGirl(new Girl(0,15,"a"));
	}
	
	@RequestMapping("/delGirl")
	public int deleteGirl(Integer id){
		return mapper1.deleteGirl(id);
	}
	
	@RequestMapping("/uptGirl")
	public int uptGirl(Integer id,Integer age,String cupSize){
		return mapper1.updateGirl(new Girl(id,age,cupSize));
	}
}
现在按照Controller去访问服务器就可以在一个项目中访问多个数据库了。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值