springboot集成mybatisPlus+多數據源的實現示例

該項目主要實現mybatisplus、多數據源、lombok、druid的集成

主要參考 https://mp.baomidou.com/guide/quick-start.html
項目地址:https://github.com/Blankwhiter/mybatisplus-springboot release1.0

項目結構:

在這裡插入圖片描述

一、創建表以及測試數據

CREATE TABLE user
(
	id VARCHAR(32) 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 '郵箱',
	PRIMARY KEY (id)
);


INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');

二、引入項目依賴,加入配置,修改啟動類,編寫實體類和mapper對象(讀者可以根據自動生成工具生成這塊代碼)

1.引入依賴

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>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.example</groupId>
  <artifactId>mybatisplus-springboot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>mybatisplus-springboot</name>
  <description>Demo project for Spring Boot</description>

  <properties>
    <java.version>1.8</java.version>
    <mysql.version>6.0.6</mysql.version>
    <mybatisplus.boot.version>3.1.0</mybatisplus.boot.version>
    <druid.version>1.1.10</druid.version>
    <dynamic.datasource.boot.version>2.5.4</dynamic.datasource.boot.version>
  </properties>

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

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>

    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-boot-starter</artifactId>
      <version>${mybatisplus.boot.version}</version>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-starter</artifactId>
      <version>${druid.version}</version>
    </dependency>

    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
      <version>${dynamic.datasource.boot.version}</version>
    </dependency>

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


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

</project>

2.編寫配置

application.yml

spring:
 autoconfigure:
  exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure # 為瞭某些版本的springboot @SpringBootApplication(exclude= {DataSourceAutoConfiguration.class}) 無法生效
 datasource:
  dynamic:
   primary: master #設置默認的數據源或者數據源組,默認值即為master,如果讀者隻是單數據源隻需要註釋掉slave相關配置即可,這裡為瞭方便演示master與slave保持相同
   datasource:
    master:
     url: jdbc:mysql://localhost:3306/test?serverTimezone=Hongkong&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false # serverTimezone=Hongkong 需要填上時區
     username: root
     password: 111111
     driverClassName: com.mysql.cj.jdbc.Driver
    slave:
     url: jdbc:mysql://localhost:3306/test?serverTimezone=Hongkong&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false # serverTimezone=Hongkong 需要填上時區
     username: root
     password: 111111
     driverClassName: com.mysql.cj.jdbc.Driver
   initial-size: 10 # 以下是連接池配置
   max-active: 100
   min-idle: 10
   max-wait: 60000
   pool-prepared-statements: true
   max-pool-prepared-statement-per-connection-size: 20
   time-between-eviction-runs-millis: 60000
   min-evictable-idle-time-millis: 300000
   #validation-query: SELECT 1
   test-while-idle: true
   test-on-borrow: false
   test-on-return: false
   stat-view-servlet:
    enabled: true
    url-pattern: /druid/*
    login-username: druid
    login-password: 123456
   filter:
    stat:
     log-slow-sql: true
     slow-sql-millis: 1000
     merge-sql: false
    wall:
     config:
      multi-statement-allow: true



#mybatis plus
mybatis-plus:
 mapper-locations: classpath:mapper/**/*.xml
 #實體掃描,多個package用逗號或者分號分隔
 typeAliasesPackage: com.example.mybatisplus.entity
 check-config-location: true
 configuration:
  #是否開啟自動駝峰命名規則(camel case)映射
  map-underscore-to-camel-case: true
  #全局地開啟或關閉配置文件中的所有映射器已經配置的任何緩存
  cache-enabled: false
  call-setters-on-nulls: true
  #配置JdbcTypeForNull, oracle數據庫必須配置
  jdbc-type-for-null: 'null'
  #MyBatis 自動映射時未知列或未知屬性處理策略 NONE:不做任何處理 (默認值), WARNING:以日志的形式打印相關警告信息, FAILING:當作映射失敗處理,並拋出異常和詳細信息
  auto-mapping-unknown-column-behavior: warning
 global-config:
  banner: false
  db-config:
   #主鍵類型 0:"數據庫ID自增", 1:"未設置主鍵類型",2:"用戶輸入ID (該類型可以通過自己註冊自動填充插件進行填充)", 3:"全局唯一ID (idWorker), 4:全局唯一ID (UUID), 5:字符串全局唯一ID (idWorker 的字符串表示)";
   id-type: UUID
   #字段驗證策略 IGNORED:"忽略判斷", NOT_NULL:"非NULL判斷", NOT_EMPTY:"非空判斷", DEFAULT 默認的,一般隻用於註解裡(1. 在全局裡代表 NOT_NULL,2. 在註解裡代表 跟隨全局)
   field-strategy: NOT_EMPTY
   #數據庫大寫下劃線轉換
   capital-mode: true
   #邏輯刪除值
   logic-delete-value: 0
   #邏輯未刪除值
   logic-not-delete-value: 1

server:
 port: 7000

3.修改啟動類

MybatisplusSpringbootApplication.java

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class}) //去掉springboot 默認的數據源配置
@MapperScan("com.example.mybatisplus.mapper") //掃描mapper的包,或者讀者可以在對應的mapper上加上@Mapper的註解
public class MybatisplusSpringbootApplication {

  public static void main(String[] args) {
    SpringApplication.run(MybatisplusSpringbootApplication.class, args);
  }
}

4.編寫實體

4.1 user.java

import lombok.Data;
/**
 * user 實體類
 */
@Data
public class User {
  private String id;
  private String name;
  private Integer age;
  private String email;
}

註:讀者請自行在開發工具安裝lombok插件,或者去掉@data註解換成setter getter方法即可

4.2 UserMapper.java

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.mybatisplus.entity.User;

/**
 * 用戶mapper
 */
@DS("slave") //這裡是配置數據源註解,默認是master
public interface UserMapper extends BaseMapper<User> {
}

三、編寫測試用例

import com.example.mybatisplus.entity.User;
import com.example.mybatisplus.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * 簡單的測試增刪改查
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisplusSpringbootApplicationTests {


  @Autowired
  private UserMapper userMapper;

  @Test
  public void addUser() {
    User user = new User();
    user.setAge(200);
    user.setEmail("[email protected]");
    user.setName("belongHuang");
    userMapper.insert(user);
  }

  @Test
  public void updateUser() {
    User user = userMapper.selectById(1);
    user.setAge(300);
    int i = userMapper.updateById(user);
    if (i>0) {
      System.out.println("修改成功");
    }else {
      System.out.println("修改失敗");
    }
  }

  @Test
  public void deleteUser() {
    int i = userMapper.deleteById(1);
    if (i>0) {
      System.out.println("刪除成功");
    }else {
      System.out.println("刪除失敗");
    }
  }
  @Test
  public void selectUser() {
    List<User> users = userMapper.selectList(null);
    users.stream().map(User::getName).forEach(System.out::println);//打印出所用用戶名字
  }
}

本文側重點於集成,更多功能移步至官網。

到此這篇關於springboot集成mybatisPlus+多數據源的實現示例的文章就介紹到這瞭,更多相關springboot mybatisPlus多數據源內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: