springboot整合Mybatis-plus


1.說明

Mybatis-Plus是一個Mybatis框架的增強插件,根據官方描述(https://mybatis.plus/guide/),MP只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑。並且只需簡單配置,即可快速進行 CRUD 操作,從而節省大量時間。代碼生成、分頁、性能分析等功能一應俱全,最新已經更新到了3.1.1版本了,3.X系列支持lambda語法,讓我在寫條件構造的時候少了很多的"魔法值",從代碼結構上更簡潔了。下面開始動手創建自己的項目把!!

2.創建springboot項目

按下圖步驟,創建一個springboot項目。我是創建了一個父子工程,創建了普通的maven項目,在項目下創建不同的springboot項目,也可以直接創建spring boot項目。

2.1創建項目

2.2選擇Spring Initializr(springboot項目)

 

2.3配置屬性,完成點擊next

 

 2.4選擇依賴,也可以不選擇,稍后在pom文件里添加

 2.5項目啟動類

 

 3.Pom文件添加依賴

<dependencies>
    <!--SpringMVC模式的web應用-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--mysql驅動-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!--jdbc 數據庫連接-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!-- 引入阿里數據庫連接池 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.6</version>
    </dependency>
    <!--lombok-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <!-- mybatisPlus 核心庫 -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.1.0</version>
    </dependency>
    <!--測試-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

4.配置文件

在resource目錄下新建,application.yml文件,配置數據庫連接驅動,日志級別。配置如下。

# 配置端口
server:
port: 8081
spring:
# 配置數據源
datasource:
url: jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
# mybatis-plus相關配置
mybatis-plus:
# xml掃描,多個目錄用逗號或者分號分隔(告訴 Mapper 所對應的 XML 文件位置)
mapper-locations: classpath:com.liyh.mapper/*.xml
# 以下配置均有默認值,可以不設置
global-config:
db-config:
#主鍵類型 AUTO:"數據庫ID自增" INPUT:"用戶輸入ID",ID_WORKER:"全局唯一ID (數字類型唯一ID)", UUID:"全局唯一ID UUID";
id-type: auto
#字段策略 IGNORED:"忽略判斷" NOT_NULL:"非 NULL 判斷") NOT_EMPTY:"非空判斷"
field-strategy: NOT_EMPTY
#數據庫類型
db-type: MYSQL
configuration:
# 是否開啟自動駝峰命名規則映射:從數據庫列名到Java屬性駝峰命名的類似映射
map-underscore-to-camel-case: true
# 如果查詢結果中包含空值的列,則 MyBatis 在映射的時候,不會映射這個字段
call-setters-on-nulls: true
# 這個配置會將執行的sql打印出來,在開發或測試的時候可以用
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 日志級別
logging:
level:
root: info

數據庫表

/*
 Navicat Premium Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 50622
 Source Host           : localhost:3306
 Source Schema         : db1

 Target Server Type    : MySQL
 Target Server Version : 50622
 File Encoding         : 65001

 Date: 28/08/2020 11:32:49
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `birthday` date NULL DEFAULT NULL,
  `gender` varchar(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `username` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `password` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `remark` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `station` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `telephone` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES (1, '2020-06-04', '1', 'admin', '$2a$10$qnWeSm.dqxgPXTeQlM.rR.CjezneVtUuIYg0TfPHzWQPy2hyc3dJq', '系統管理員', '正常', '888888', '管理員');
INSERT INTO `t_user` VALUES (2, '2020-06-04', '2', 'xiaoming', '$2a$10$qnWeSm.dqxgPXTeQlM.rR.CjezneVtUuIYg0TfPHzWQPy2hyc3dJq', '營養健康師', '正常', '666666', '小明');

SET FOREIGN_KEY_CHECKS = 1;

5.開始編寫代碼及測試

5.1 創建entity

 

實體類:

package com.liyh.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;

/**
 * 用戶實體類
 * @Author: liyh
 * @Date: 2020/8/28 11:39
 */
@Data
@TableName(value = "t_user")
public class User implements Serializable{
    private Integer id; // 主鍵
    private Date birthday; // 生日
    private String gender; // 性別
    private String username; // 用戶名,唯一
    private String password; // 密碼
    private String remark; // 備注
    private String station; // 狀態
    private String telephone; // 聯系電話
    private String name; // 姓名

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

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

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public String getStation() {
        return station;
    }

    public void setStation(String station) {
        this.station = station;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

}
User

5.2 創建mapper

在mapper包中創建UserMapper接口,並繼承mybatisPlus的BaseMapper,如下圖

5.3 在啟動類添加mapper掃描

5.4 創建service和impl

 

注意:在UserServiceImpl類,必須加上@Service注解,否則會報錯 Field userService in com.liyh.mybatisplus.controller.UserController required

5.5 創建controller

這里我們看到,service中我們沒有寫任何方法,MyBatis-Plus官方封裝了許多基本CRUD的方法,可以直接使用大量節約時間,MP共通方法詳見IService,ServiceImpl,BaseMapper源碼,寫入操作在ServiceImpl中已有事務綁定,這里我們舉一些常用的方法演示。

package com.liyh.controller;

import com.liyh.entity.User;
import com.liyh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;

/**
 * @Author: liyh
 * @Date: 2020/8/28 11:52
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    /**
     * 根據用戶id查詢用戶信息
     * @param userId
     * @return
     */
    //http://localhost:8080/user/getInfo?userId=1
    @RequestMapping("/getInfo")
    public User getInfo(String userId){
        User user = userService.getById(userId);
        System.out.println(user.getName());
        return user;
    }

    /**
     * 查詢所有信息
     * @return
     */
    //http://localhost:8080/user/getUserList
    @RequestMapping("/getUserList")
    public List<User> getUserList(){
        return userService.list();
    }

    /**
     * 新增用戶信息
     */
    //http://localhost:8080/user/saveInfo
    @RequestMapping("/saveInfo")
    public void saveInfo(){
        User user = new User();
        user.setBirthday(new Date());
        user.setGender("1");
        user.setUsername("apple");
        user.setPassword("apple");
        user.setRemark("消費大師");
        user.setStation("凍結");
        user.setTelephone("111111");
        user.setName("平鍋");
        userService.save(user);
    }
}

5.6 項目總體結構

5.7 啟動項目進行測試

5.7.1 測試getInfo接口

/**
     * 根據用戶id查詢用戶信息
     * @param userId
     * @return
     */
    //http://localhost:8080/user/getInfo?userId=1
    @RequestMapping("/getInfo")
    public User getInfo(String userId){
        User user = userService.getById(userId);
        System.out.println(user.getName());
        return user;
    }

5.7.2 測試getUserList接口

/**
     * 查詢所有信息
     * @return
     */
    //http://localhost:8080/user/getUserList
    @RequestMapping("/getUserList")
    public List<User> getUserList(){
        return userService.list();
    }

5.7.3 測試save接口

6. 數據庫

7. 項目地址:https://gitee.com/liyhGitee/springboot

發布自己的項目到git,瀏覽:https://www.cnblogs.com/liyhbk/p/13578717.html

8. 結束語

上天的程序員后續分享,關於springboot的更多功能和使用,每一個截圖都是實戰的結果,謝謝閱讀,點波關注喲!!!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM