一、前言

  • 什么时候需要用到多数据源配置?
    当你的项目需要访问多个数据库的时候

  • 本篇开发环境
    1、操作系统: Windows 10 X64
    2、Java SDK: jdk-8u141
    3、Maven:3.5
    4、IDE:IntelliJ IDEA 2017
    5、Spring Boot:1.5.6

本项目构建基于:https://ken.io/note/springboot-course-basic-curd-annotation

二、多数据源配置

  • 创建数据库&表

1.1、手动创建数据库test
1.2:创建表:note

DROP TABLE IF EXISTS `note`;
CREATE TABLE `note` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) DEFAULT NULL,
  `body` longtext,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
  • 修改数据库连接配置(application.yml)
#数据库连接配置
courseDataSource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/course?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8
    username: root
    password: root

testDataSource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8
    username: root
    password: root
  • 调整model

1、在io.ken.springboot.course.model下新建两个package:course、test
2、将User.java移动到io.ken.springboot.course.model.course
3、在io.ken.springboot.course.model.test下新建Note.java

package io.ken.springboot.course.model.test;

public class Note {

    private int id;

    private String title;

    private String body;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }
}
  • 调整dao

1、在io.ken.springboot.course.dao下新建两个package:course、test
2、将UserMapper.java移动到io.ken.springboot.course.dao.course
3、在io.ken.springboot.course.dao.test下新建NoteMapper.java

package io.ken.springboot.course.dao.test;

import io.ken.springboot.course.model.test.Note;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface NoteMapper {

    @Select("SELECT * FROM note")
    List<Note> queryAll();
}
  • 配置数据源

1、在io.ken.springboot.course下新建package:config
2、在io.ken.springboot.course.config下创建CourseDbConfig.java

package io.ken.springboot.course.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.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 javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "io.ken.springboot.course.dao.course", sqlSessionFactoryRef = "courseSqlSessionFactory")
public class CourseDbConfig {

    @Bean(name = "courseDataSource")
    @ConfigurationProperties(prefix = "courseDataSource")
    @Primary
    public DataSource courseDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "courseSqlSessionFactory")
    @Primary
    public SqlSessionFactory courseSqlSessionFactory(@Qualifier("courseDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

}

3、在io.ken.springboot.course.config下创建TestDbConfig.java

package io.ken.springboot.course.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.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "io.ken.springboot.course.dao.test", sqlSessionFactoryRef = "testSqlSessionFactory")
public class TestDbConfig {

    @Bean(name = "testDataSource")
    @ConfigurationProperties(prefix = "testDataSource")
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "testSqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("testDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

}
  • 创建NoteController并提供API
package io.ken.springboot.course.controller;

import io.ken.springboot.course.dao.test.NoteMapper;
import io.ken.springboot.course.model.test.Note;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/note")
public class NoteController {

    @Autowired
    NoteMapper noteMapper;

    @RequestMapping("/queryall")
    @ResponseBody
    List<Note> queryAll() {
        return noteMapper.queryAll();
    }
}
  • API测试
API 示例
添加用户 /user/add?name=tom&age=1&hobby=football
更新用户 /user/updatebyid?name=ken&age=18&hobby=coding&id=1
查询指定用户 /user/querybyid?id=1
查询所有用户 /user/queryall
删除指定用户 /user/delbyid?id=2
查询所有日志 /note/queryall

本文代码示例:https://github.com/ken-io/springboot-course/tree/master/chapter-02-03