當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot2.0整合Mybatis-Plus多数据源
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot2.0整合Mybatis-Plus多数据源
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、pom依賴
- 二、application.yml多數據源配置
- 三、持久層
- 3.1. UserMapper 接口
- 3.2. 接口映射UserMapper.xml(可以不寫)
- 四、邏輯處理層
- 4.1. IUserService 接口
- 4.2. 接口實現類IUserServiceImpl
- 五、通用返回對象封裝
- 六、測試UserController
- 七、啟動類加掃描mapper注解
- 八、數據庫腳本
- 8.1. masterdb.sql
- 8.2. slavedb.sql
- 九、測試驗證
- 9.1. 主庫新增用戶
- 9.2. 從庫新增用戶
- 9.3. 獲取主庫用戶列表
- 9.4. 獲取從庫用戶列表
- 9.5.
一、pom依賴
需要引入與SpringBoot整合好的動態數據源依賴,以及mybatis-plus相關依賴包
<!--SpringBoot mvc啟動器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 多數據源依賴 --><dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>${dynamic-datasource.version}</version></dependency><!--lombok 簡化java代碼--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.10</version></dependency><!-- Spring Boot Mybatis plus 依賴 --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.2.0</version></dependency><!--Mysql數據庫驅動--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</version><scope>runtime</scope></dependency><!--單元測試--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>二、application.yml多數據源配置
直接復制到你的項目中即可,通過primary來指定默認數據源,配置如下:
server:port: 80# 數據源配置 spring:datasource:dynamic:primary: master #設置默認的數據源datasource:master:username: rootpassword: rooturl: jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8driver-class-name: com.mysql.cj.jdbc.Driver# 從數據源配置slave:username: rootpassword: rooturl: jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8driver-class-name: com.mysql.cj.jdbc.Drivermp-enabled: true# 數據源加載日志 logging:level:com.xkcoding.multi.datasource.mybatis: debug三、持久層
3.1. UserMapper 接口
public interface UserMapper extends BaseMapper<User> { }3.2. 接口映射UserMapper.xml(可以不寫)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.gblfy.springboot.mybatisplus.entity.User"> </mapper>四、邏輯處理層
4.1. IUserService 接口
import com.baomidou.mybatisplus.extension.service.IService; import com.gblfy.springboot.mybatisplus.entity.User;import java.util.List;public interface IUserService extends IService<User> {/*** 往從庫中插入數據** @param user*/Integer addUserToSlave(User user);/*** 主庫插入** @param user*/Integer addUserToMaster(User user);/*** 獲取主庫用戶列表** @return*/List<User> findMasterUserList();/*** 獲取從庫用戶列表** @return*/List<User> findSlaveUserList(); }4.2. 接口實現類IUserServiceImpl
import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.gblfy.springboot.mybatisplus.entity.User; import com.gblfy.springboot.mybatisplus.mapper.UserMapper; import com.gblfy.springboot.mybatisplus.service.IUserService; import org.springframework.stereotype.Service;import java.util.List;/*** @author gblfy* @ClassNme IUserServiceImpl* @Description TODO* @Date 2019/12/8 10:21* @version1.0*/ @Service @DS("master") public class IUserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {@DS("slave")@Overridepublic Integer addUserToSlave(User user) {return null;}@Overridepublic Integer addUserToMaster(User user) {return null;}@Overridepublic List<User> findMasterUserList() {return null;}@DS("slave")@Overridepublic List<User> findSlaveUserList() {return null;} }五、通用返回對象封裝
/*** 公共返回實體類*/ @Data public class ResultObject {/*** 可為數組或字符串等,可記錄錯誤信息或正常返回的相關信息*/private Object message;/*** 返回碼 200代表正常 1代表失敗*/private int code;private Object result;}六、測試UserController
import com.gblfy.springboot.mybatisplus.entity.User; import com.gblfy.springboot.mybatisplus.service.IUserService; import com.gblfy.springboot.mybatisplus.utils.ResultObject; import lombok.Data; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;/*** @author: gblfy* @desc: 用戶控制層* @date: 2019/12/8 10:25*/ @RestController @RequestMapping("/user") @Data public class UserController {@Autowiredprivate IUserService userService;/*** 主庫新增用戶* @param user* @return*/@GetMapping("addUserToMaster")public Object addUserToMaster(User user){ResultObject resultObject = new ResultObject();try {User userMaster = User.builder().name(user.getName()).age(user.getAge()).email(user.getEmail()).build();resultObject.setResult(userService.addUserToMaster(userMaster));resultObject.setCode(200);resultObject.setMessage("主庫新增用戶成功");} catch (Exception e) {resultObject.setCode(-1);resultObject.setMessage("主庫新增用戶失敗");e.printStackTrace();}return resultObject;}/*** 從庫新增用戶* @param user* @return*/@GetMapping("addUserToSlave")public Object addUserToSlave(User user){ResultObject resultObject = new ResultObject();try {User userSlave = User.builder().name(user.getName()).age(user.getAge()).email(user.getEmail()).build();resultObject.setResult(userService.addUserToSlave(userSlave));resultObject.setCode(200);resultObject.setMessage("從庫新增用戶成功");} catch (Exception e) {resultObject.setCode(-1);resultObject.setMessage("從庫新增用戶失敗");e.printStackTrace();}return resultObject;}/*** 獲取主庫用戶列表* @return*/@RequestMapping("findMasterUserList")public Object findMasterUserList(){ResultObject resultObject = new ResultObject();try {resultObject.setResult(userService.findMasterUserList());resultObject.setCode(200);resultObject.setMessage("獲取主庫用戶列表成功");} catch (Exception e) {resultObject.setCode(-1);resultObject.setMessage("獲取主庫用戶列表失敗");e.printStackTrace();}return resultObject;}/*** 獲取從庫用戶列表* @return*/@RequestMapping("findSlaveUserList")public Object findSlaveUserList(){ResultObject resultObject = new ResultObject();try {resultObject.setResult(userService.findSlaveUserList());resultObject.setCode(200);resultObject.setMessage("獲取從庫用戶列表成功");} catch (Exception e) {resultObject.setCode(-1);resultObject.setMessage("獲取從庫用戶列表失敗");e.printStackTrace();}return resultObject;} }七、啟動類加掃描mapper注解
import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication @MapperScan(basePackages = "com.gblfy.springboot.mybatisplus.mapper") public class SpringbootApplication {public static void main(String[] args) {SpringApplication.run(SpringbootApplication.class, args);} }八、數據庫腳本
8.1. masterdb.sql
DROP TABLE IF EXISTS user;CREATE TABLE user (id BIGINT(20) NOT NULL COMMENT '主鍵ID',name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',age INT(11) NULL DEFAULT NULL COMMENT '年齡',email VARCHAR(50) NULL DEFAULT NULL COMMENT '郵箱',create_time DATETIME DEFAULT NULL COMMENT '創建時間',PRIMARY KEY (id) );DELETE FROM user;INSERT INTO user (id, name, age, email, create_time) VALUES (1, 'Jone', 18, 'test1@gblfy.com','2019-01-11 14:20:20'), (2, 'Jack', 20, 'test2@gblfy.com','2019-02-05 11:12:22'), (3, 'Tom', 28, 'test3@gblfy.com','2019-02-14 08:31:16'), (4, 'Sandy', 21, 'test4@gblfy.com','2019-01-14 09:15:15'), (5, 'Billie', 24, 'test5@gblfy.com','2019-01-14 09:48:16');8.2. slavedb.sql
DROP TABLE IF EXISTS user;CREATE TABLE user (id BIGINT(20) NOT NULL COMMENT '主鍵ID',name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',age INT(11) NULL DEFAULT NULL COMMENT '年齡',email VARCHAR(50) NULL DEFAULT NULL COMMENT '郵箱',create_time DATETIME DEFAULT NULL COMMENT '創建時間',PRIMARY KEY (id) );DELETE FROM user;INSERT INTO user (id, name, age, email, create_time) VALUES (1, 'Jone2', 18, 'test1@gblfy.com','2019-01-11 14:20:20'), (2, 'Jack2', 20, 'test2@gblfy.com','2019-02-05 11:12:22'), (3, 'Tom2', 28, 'test3@gblfy.com','2019-02-14 08:31:16'), (4, 'Sandy2', 21, 'test4@gblfy.com','2019-01-14 09:15:15'), (5, 'Billie2', 24, 'test5@gblfy.com','2019-01-14 09:48:16');九、測試驗證
9.1. 主庫新增用戶
http://localhost/user/addUserToMaster?name=gblfy&age=66&email=gbly02@gmail.com9.2. 從庫新增用戶
http://localhost/user/addUserToSlave?name=gblfy02&age=66&email=gbly02@gmail.com9.3. 獲取主庫用戶列表
http://localhost/user/findMasterUserList9.4. 獲取從庫用戶列表
http://localhost/user/findSlaveUserList9.5.
http://localhost/user/addUserToMaster?name=gblfy&age=66&email=gbly02@gmail.com總結
以上是生活随笔為你收集整理的SpringBoot2.0整合Mybatis-Plus多数据源的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: flowable实战(八)flowabl
- 下一篇: IDEA中新建项目Static Web