欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot 開(kāi)發(fā)提速神器 Lombok+MybatisPlus+SwaggerUI

 更新時(shí)間:2021年10月22日 17:01:41   作者:陳彥斌  
這篇文章主要介紹了SpringBoot 開(kāi)發(fā)提速神器 Lombok+MybatisPlus+SwaggerUI,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

導(dǎo)讀

  • Lombok:可以讓你的POJO代碼特別簡(jiǎn)潔,不止簡(jiǎn)單在BO/VO/DTO/DO等大量使用,還有設(shè)計(jì)模式,對(duì)象對(duì)比等
  • MybatisPlus:增加版Mybatis,基礎(chǔ)的數(shù)據(jù)庫(kù)CRUD、分頁(yè)等可以直接生成使用,避免了大量的重復(fù)低效代碼,還有數(shù)據(jù)庫(kù)自動(dòng)Java類(lèi),sql文件等等,比傳統(tǒng)的更賤簡(jiǎn)介易用
  • SwaggerUI:接口文檔自動(dòng)生成,對(duì)接前端和測(cè)試更加方便,基于業(yè)界的OpennApi規(guī)范,采用Swagger3.x版本。

技術(shù)棧

  SpringBoot2.4+ MybatisPlus+Lombok+Swagger3.x+jdk8+IDEA

在線構(gòu)建項(xiàng)目

點(diǎn)我直達(dá)

什么是lombok

官網(wǎng)

點(diǎn)我直達(dá)

  一個(gè)優(yōu)秀的Java代碼庫(kù),簡(jiǎn)化了Java的編碼,為Java代碼的精簡(jiǎn)提供了一種方式

添加依賴(lài)

 <!--lombok-->
 <dependency>
 <groupId>org.projectlombok</groupId>
 <artifactId>lombok</artifactId>
 <version>1.18.16</version>
 <!--scope=provided,說(shuō)明它是在編譯階段生效,不需要打入包中,Lombok在編譯期將帶Lombok注解的Java文件正確編譯為完整的Class文件-->
 <scope>provided</scope>
 </dependency>

常見(jiàn)注解@Getter/@Setter#

  • 作用類(lèi)上,生成所有成員變量的getter/setter方法
  • 作用于成員變量上,生成該成員變量的getter/setter方法
  • 方法控制訪問(wèn)級(jí)別set和get注解加上@Getter(AccessLevel.PROTECTED)

編譯查看字節(jié)碼

mvn compile

package com.ybchen.shopmanager.model;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

/**
 * @Description:
 * @Author:chenyanbin
 * @Date:2021/3/2 下午9:43
 * @Versiion:1.0
 */
@Getter
@Setter
public class User {
 //不想生成get方法
 @Getter(AccessLevel.NONE)
 int id;
 //只會(huì)去生成get
 final String name = "alex";
 String phone;
 //靜態(tài)成員變量不會(huì)生成set/get方法
 static final String pwd = "123";
}

@NonNull

作用于方法上或者屬性,用于非空判斷,如果為空則拋異常

@NoArgsContructor

生成無(wú)參構(gòu)造器

@AllArgsConstructor

生成全參構(gòu)造器

@RequiredArgsConstructor

指定參數(shù)的構(gòu)造函數(shù),有以下的特征的字段

  • final類(lèi)型未被初始化的屬性,標(biāo)記了@NonNull的屬性
  • 注意:@NoArgsConstructor不能添加

@ToStringList或者其他集合調(diào)試不方便控制臺(tái)或者日志輸出對(duì)象,默認(rèn)打印的是內(nèi)存地址作用于類(lèi),覆蓋默認(rèn)的toString()方法

不包括某個(gè)字段

@ToString(exclude={"age"})

只輸出某個(gè)字段

@ToString(of={"name"})

為什么對(duì)象要重寫(xiě)hashcode和equal方法

HashCode方法

  • 頂級(jí)類(lèi)Object里面的方法,所有類(lèi)都是繼承Object的,返回值Int類(lèi)型
  • 根據(jù)一定的hash規(guī)則(存儲(chǔ)地址,字段,或者長(zhǎng)度等),映射成一個(gè)數(shù)值,即散列值

Equals方法

  • 頂級(jí)類(lèi)Object里面的方法,所有類(lèi)都是繼承Object的,返回值boolean類(lèi)型
  • 根據(jù)自定義的匹配規(guī)則,用于匹配兩個(gè)對(duì)象是否一樣,一般邏輯如下

1、判斷地址是否一樣
2、非空判斷和class類(lèi)型判斷
3、強(qiáng)轉(zhuǎn)
4、對(duì)象里面的字段一一匹配

解析

  如果兩個(gè)對(duì)象相等,那么它們的hashCode()值一定相同。如果兩個(gè)對(duì)象hashCode()相等,它們并不一定相等。在散列表中hashCode()相等,即兩個(gè)鍵值的哈希值相等。然后哈希值相等,并不一定得出鍵值對(duì)相等,就出現(xiàn)所謂的哈希沖突場(chǎng)景,還需要equals方法判斷對(duì)象是否相等。

應(yīng)用場(chǎng)景

  當(dāng)向集合中插入對(duì)象時(shí),如何判別在集合中是否已經(jīng)存在該對(duì)象,比如Set確保存儲(chǔ)對(duì)象的唯一值,并判斷是否同一個(gè)對(duì)象呢?

依據(jù)hashCode和equals進(jìn)行判斷
所以Set存儲(chǔ)的對(duì)象必須重寫(xiě)這兩個(gè)方法,判斷兩個(gè)對(duì)象是否一樣
首先判斷插入對(duì)象的hashCode值是否存在,hashCode值不存在則直接插入集合;值存在則還需要判斷equals方法判斷對(duì)象是否相等

@EqualsAndHashCode

作用于類(lèi),覆蓋默認(rèn)的equals和hashCode,作用于全部屬性

不包含某個(gè)屬性

@EqualsAndHashCode(exclude={"id"})

只輸出某個(gè)屬性

@EqualsAndHashCode(of={"id"})

@Data

作用于類(lèi)上,是以下注解的集合

@ToString

@EqualsAndHashCode

@Getter

@Setter

@RequiredArgsConstructor

@Builder場(chǎng)景:當(dāng)一個(gè)bean類(lèi)重載了多個(gè)構(gòu)造方法時(shí),并且參數(shù)隨機(jī)使用時(shí),考慮使用構(gòu)造者模式

@Lof/@Slf4j作用于類(lèi)上,生成日志變量,用于記錄日志

MybatisPlus介紹

  • 官網(wǎng):點(diǎn)我直達(dá)
  • 是一個(gè)mybatis的增強(qiáng)工具,在Mybatis的基礎(chǔ)上只做強(qiáng)增不做改變,為簡(jiǎn)化開(kāi)發(fā),提高效率

數(shù)據(jù)庫(kù)腳本

/*
 Navicat Premium Data Transfer

 Source Server  : localhost
 Source Server Type : MySQL
 Source Server Version : 50728
 Source Host  : localhost:3306
 Source Schema  : shop

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

 Date: 04/03/2021 22:17:20
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for address
-- ----------------------------
DROP TABLE IF EXISTS `address`;
CREATE TABLE `address` (
 `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
 `user_id` bigint(20) DEFAULT NULL COMMENT '用戶id',
 `default_status` int(1) DEFAULT NULL COMMENT '是否默認(rèn)收貨地址:0->否;1->是',
 `receive_name` varchar(64) DEFAULT NULL COMMENT '收發(fā)貨人姓名',
 `phone` varchar(64) DEFAULT NULL COMMENT '收貨人電話',
 `province` varchar(64) DEFAULT NULL COMMENT '省/直轄市',
 `city` varchar(64) DEFAULT NULL COMMENT '市',
 `region` varchar(64) DEFAULT NULL COMMENT '區(qū)',
 `detail_address` varchar(200) DEFAULT NULL COMMENT '詳細(xì)地址',
 `create_time` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='電商-公司收發(fā)貨地址表';

-- ----------------------------
-- Records of address
-- ----------------------------
BEGIN;
COMMIT;

-- ----------------------------
-- Table structure for banner
-- ----------------------------
DROP TABLE IF EXISTS `banner`;
CREATE TABLE `banner` (
 `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
 `img` varchar(524) DEFAULT NULL COMMENT '圖片',
 `url` varchar(524) DEFAULT NULL COMMENT '跳轉(zhuǎn)地址',
 `weight` int(11) DEFAULT NULL COMMENT '權(quán)重',
 `version` int(11) DEFAULT '1',
 `deleted` int(11) DEFAULT '0' COMMENT '0是未刪除,1是已經(jīng)刪除',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of banner
-- ----------------------------
BEGIN;
INSERT INTO `banner` VALUES (1, 'https://images.cnblogs.com/cnblogs_com/chenyanbin/1560326/o_qianxun.jpg', 'https://www.cnblogs.com/chenyanbin/', 1, 2, 1);
INSERT INTO `banner` VALUES (2, 'https://images.cnblogs.com/cnblogs_com/chenyanbin/1560326/o_qianxun.jpg', 'https://www.cnblogs.com/chenyanbin/', 3, 1, 0);
INSERT INTO `banner` VALUES (3, 'https://images.cnblogs.com/cnblogs_com/chenyanbin/1560326/o_qianxun.jpg', 'https://www.cnblogs.com/chenyanbin/', 2, 1, 0);
INSERT INTO `banner` VALUES (7, 'werw', 'https://images.cnblogs.com/cnblogs_com/chenyanbin/1560326/o_qianxun.jpg', 2, 1, 0);
INSERT INTO `banner` VALUES (8, '666666', 'https://images.cnblogs.com/cnblogs_com/chenyanbin/1560326/o_qianxun.jpg', 2, 1, 0);
INSERT INTO `banner` VALUES (9, 'sdfds', 'https://images.cnblogs.com/cnblogs_com/chenyanbin/1560326/o_qianxun.jpg', 2, 1, 0);
INSERT INTO `banner` VALUES (10, '323232', 'https://images.cnblogs.com/cnblogs_com/chenyanbin/1560326/o_qianxun.jpg', 2, 1, 0);
INSERT INTO `banner` VALUES (11, '532', 'https://images.cnblogs.com/cnblogs_com/chenyanbin/1560326/o_qianxun.jpg', 2, 1, 0);
INSERT INTO `banner` VALUES (12, '6666', 'https://images.cnblogs.com/cnblogs_com/chenyanbin/1560326/o_qianxun.jpg', 2, 1, 0);
COMMIT;

-- ----------------------------
-- Table structure for coupon
-- ----------------------------
DROP TABLE IF EXISTS `coupon`;
CREATE TABLE `coupon` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
 `category` varchar(11) DEFAULT NULL COMMENT '優(yōu)惠卷類(lèi)型[NEW_USER注冊(cè)贈(zèng)券,TASK任務(wù)卷,PROMOTION促銷(xiāo)劵]',
 `publish` varchar(11) DEFAULT NULL COMMENT '發(fā)布狀態(tài), PUBLISH發(fā)布,DRAFT草稿,OFFLINE下線',
 `coupon_img` varchar(524) DEFAULT NULL COMMENT '優(yōu)惠券圖片',
 `coupon_title` varchar(128) DEFAULT NULL COMMENT '優(yōu)惠券標(biāo)題',
 `price` decimal(16,2) DEFAULT NULL COMMENT '抵扣價(jià)格',
 `user_limit` int(11) DEFAULT NULL COMMENT '每人限制張數(shù)',
 `start_time` datetime DEFAULT NULL COMMENT '優(yōu)惠券開(kāi)始有效時(shí)間',
 `end_time` datetime DEFAULT NULL COMMENT '優(yōu)惠券失效時(shí)間',
 `publish_count` int(11) DEFAULT NULL COMMENT '優(yōu)惠券總量',
 `stock` int(11) DEFAULT '0' COMMENT '庫(kù)存',
 `add_one` int(11) DEFAULT NULL COMMENT '是否疊加0是不行,1是可以',
 `create_time` datetime DEFAULT NULL,
 `condition_price` decimal(16,2) DEFAULT NULL COMMENT '滿多少才可以使用',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of coupon
-- ----------------------------
BEGIN;
COMMIT;

-- ----------------------------
-- Table structure for product
-- ----------------------------
DROP TABLE IF EXISTS `product`;
CREATE TABLE `product` (
 `id` bigint(11) unsigned NOT NULL AUTO_INCREMENT,
 `title` varchar(128) DEFAULT NULL COMMENT '標(biāo)題',
 `cover_img` varchar(128) DEFAULT NULL COMMENT '封面圖',
 `detail` varchar(256) DEFAULT '' COMMENT '詳情',
 `old_price` decimal(16,2) DEFAULT NULL COMMENT '老價(jià)格',
 `price` decimal(16,2) DEFAULT NULL COMMENT '新價(jià)格',
 `stock` int(11) DEFAULT NULL COMMENT '庫(kù)存',
 `create_time` datetime DEFAULT NULL COMMENT '創(chuàng)建時(shí)間',
 `lock_stock` int(11) DEFAULT '0' COMMENT '鎖定庫(kù)存',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of product
-- ----------------------------
BEGIN;
COMMIT;

-- ----------------------------
-- Table structure for product_order
-- ----------------------------
DROP TABLE IF EXISTS `product_order`;
CREATE TABLE `product_order` (
 `id` bigint(11) NOT NULL AUTO_INCREMENT,
 `out_trade_no` varchar(64) DEFAULT NULL COMMENT '訂單唯一標(biāo)識(shí)',
 `state` varchar(11) DEFAULT NULL COMMENT 'NEW 未支付訂單,PAY已經(jīng)支付訂單,CANCEL超時(shí)取消訂單',
 `create_time` datetime DEFAULT NULL COMMENT '訂單生成時(shí)間',
 `total_fee` decimal(16,2) DEFAULT NULL COMMENT '訂單總金額',
 `pay_fee` decimal(16,2) DEFAULT NULL COMMENT '訂單實(shí)際支付價(jià)格',
 `pay_type` varchar(64) DEFAULT NULL COMMENT '支付類(lèi)型,微信-銀行-支付寶',
 `nickname` varchar(64) DEFAULT NULL COMMENT '昵稱(chēng)',
 `head_img` varchar(524) DEFAULT NULL COMMENT '頭像',
 `user_id` int(11) DEFAULT NULL COMMENT '用戶id',
 `del` int(5) DEFAULT '0' COMMENT '0表示未刪除,1表示已經(jīng)刪除',
 `update_time` datetime DEFAULT NULL COMMENT '更新時(shí)間',
 `order_type` varchar(32) DEFAULT NULL COMMENT '訂單類(lèi)型 DAILY普通單,PROMOTION促銷(xiāo)訂單',
 `receiver_address` varchar(1024) DEFAULT NULL COMMENT '收貨地址 json存儲(chǔ)',
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of product_order
-- ----------------------------
BEGIN;
COMMIT;

-- ----------------------------
-- Table structure for product_order_item
-- ----------------------------
DROP TABLE IF EXISTS `product_order_item`;
CREATE TABLE `product_order_item` (
 `id` bigint(11) unsigned NOT NULL AUTO_INCREMENT,
 `product_order_id` bigint(11) DEFAULT NULL COMMENT '訂單號(hào)',
 `out_trade_no` varchar(32) DEFAULT NULL,
 `product_id` bigint(11) DEFAULT NULL COMMENT '產(chǎn)品id',
 `product_name` varchar(128) DEFAULT NULL COMMENT '商品名稱(chēng)',
 `product_img` varchar(524) DEFAULT NULL COMMENT '商品圖片',
 `buy_num` int(11) DEFAULT NULL COMMENT '購(gòu)買(mǎi)數(shù)量',
 `create_time` datetime DEFAULT NULL,
 `total_fee` decimal(16,2) DEFAULT NULL COMMENT '購(gòu)物項(xiàng)商品總價(jià)格',
 `pay_fee` decimal(16,0) DEFAULT NULL COMMENT '購(gòu)物項(xiàng)商品支付總價(jià)格',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of product_order_item
-- ----------------------------
BEGIN;
COMMIT;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
 `id` bigint(11) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(128) DEFAULT NULL COMMENT '昵稱(chēng)',
 `pwd` varchar(124) DEFAULT NULL COMMENT '密碼',
 `head_img` varchar(524) DEFAULT NULL COMMENT '頭像',
 `slogan` varchar(524) DEFAULT NULL COMMENT '用戶簽名',
 `sex` tinyint(2) DEFAULT '1' COMMENT '0表示女,1表示男',
 `points` int(10) DEFAULT '0' COMMENT '積分',
 `create_time` datetime DEFAULT NULL,
 `mail` varchar(64) DEFAULT NULL COMMENT '郵箱',
 `secret` varchar(12) DEFAULT NULL COMMENT '鹽,用于個(gè)人敏感信息處理',
 PRIMARY KEY (`id`),
 UNIQUE KEY `mail_idx` (`mail`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
BEGIN;
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

pom.xml

 <!--mysql-->
 <dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
 </dependency>
 <!--mybatis plus和spring boot整合-->
 <dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-boot-starter</artifactId>
  <version>3.4.0</version>
 </dependency>
<?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 https://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.4.3</version>
 <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>com.ybchen</groupId>
 <artifactId>shop-manager</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>shop-manager</name>
 <description>Demo project for Spring Boot</description>
 <properties>
 <java.version>1.8</java.version>
 </properties>
 <dependencies>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
 </dependency>
 <!--lombok-->
 <dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.16</version>
  <!--scope=provided,說(shuō)明它是在編譯階段生效,不需要打入包中,Lombok在編譯期將帶Lombok注解的Java文件正確編譯為完整的Class文件-->
  <scope>provided</scope>
 </dependency>
 <!--mysql-->
 <dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
 </dependency>
 <!--mybatis plus和spring boot整合-->
 <dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-boot-starter</artifactId>
  <version>3.4.0</version>
 </dependency>
 </dependencies>

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

 <!-- 代碼庫(kù) -->
 <repositories>
 <repository>
  <id>maven-ali</id>
  <url>http://maven.aliyun.com/nexus/content/groups/public//</url>
  <releases>
  <enabled>true</enabled>
  </releases>
  <snapshots>
  <enabled>true</enabled>
  <updatePolicy>always</updatePolicy>
  <checksumPolicy>fail</checksumPolicy>
  </snapshots>
 </repository>
 </repositories>
 <pluginRepositories>
 <pluginRepository>
  <id>public</id>
  <name>aliyun nexus</name>
  <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
  <releases>
  <enabled>true</enabled>
  </releases>
  <snapshots>
  <enabled>false</enabled>
  </snapshots>
 </pluginRepository>
 </pluginRepositories>
</project>

完整pom.xml配置文件

application.properties

# 端口號(hào)
server.port=9999
#===========數(shù)據(jù)庫(kù)相關(guān)=============
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1/shop?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

配置SpringBoot掃描路徑

  啟動(dòng)類(lèi)上添加:@MapperScan("Mapper全包路徑")

SpringBoot整合MybatisPlus

統(tǒng)一接口返回協(xié)議

package com.ybchen.shopmanager.utils;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class JsonData implements Serializable {
 /**
 * 狀態(tài)碼 0 表示成功,1 表示處理中,-1表示失敗
 */
 private Integer code;
 /**
 * 數(shù)據(jù)
 */
 private Object data;
 /**
 * 描述信息
 */
 private String msg;

 /**
 * 成功,無(wú)傳入數(shù)據(jù)
 *
 * @return
 */
 public static JsonData buildSuccess() {
 return new JsonData(0, null, null);
 }

 /**
 * 成功,有傳入數(shù)據(jù)
 *
 * @param data 數(shù)據(jù)
 * @return
 */
 public static JsonData buildSuccess(Object data) {
 return new JsonData(0, data, null);
 }

 /**
 * 失敗,有返回錯(cuò)誤信息
 *
 * @param msg 描述信息
 * @return
 */
 public static JsonData buildError(String msg) {
 return new JsonData(-1, null, msg);
 }

 /**
 * 失敗,有狀態(tài)碼,描述信息
 *
 * @param code 狀態(tài)碼
 * @param msg 描述信息
 * @return
 */
 public static JsonData buildError(Integer code, String msg) {
 return new JsonData(code, null, msg);
 }

 /**
 * 是否返回成功
 * @param jsonData
 * @return
 */
 public static boolean isSuccess(JsonData jsonData) {
 return jsonData.getCode() == 0;
 }
}

實(shí)體類(lèi)

package com.ybchen.shopmanager.model;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

/**
 * @Description:輪播圖
 * @Author:chenyanbin
 * @Date:2021/3/4 下午11:00
 * @Versiion:1.0
 */
@Data
//數(shù)據(jù)庫(kù)表名
@TableName("banner")
public class BannerDO {
 /**
 * 主鍵
 */
 private Integer id;
 /**
 * 圖片
 */
 private String img;
 /**
 * url跳轉(zhuǎn)地址
 */
 private String url;
 /**
 * 權(quán)重
 */
 private Integer weight;
 /**
 * 版本號(hào)
 */
 private Integer version;
 /**
 * 0是未刪除,1是已經(jīng)刪除
 */
 private Integer deleted;
}

service

package com.ybchen.shopmanager.service;

import com.ybchen.shopmanager.model.BannerDO;

import java.util.List;

public interface BannerService {
 List<BannerDO> list();
}
package com.ybchen.shopmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ybchen.shopmanager.mapper.BannerMapper;
import com.ybchen.shopmanager.model.BannerDO;
import com.ybchen.shopmanager.service.BannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:輪播圖Service
 * @Author:chenyanbin
 * @Date:2021/3/4 下午11:04
 * @Versiion:1.0
 */
@Service
public class BannerServiceImpl implements BannerService {
 @Autowired
 private BannerMapper bannerMapper;
 @Override
 public List<BannerDO> list() {
 return bannerMapper.selectList(new QueryWrapper<>());
 }
}

Controller

package com.ybchen.shopmanager.controller;

import com.ybchen.shopmanager.service.BannerService;
import com.ybchen.shopmanager.utils.JsonData;
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;

/**
 * @Description:輪播圖Controller
 * @Author:chenyanbin
 * @Date:2021/3/4 下午11:06
 * @Versiion:1.0
 */
@RestController
@RequestMapping("api/v1/banner")
public class BannerController {
 @Autowired
 private BannerService bannerService;
 @GetMapping("list")
 public JsonData list(){
 return JsonData.buildSuccess(bannerService.list());
 }
}

測(cè)試

單元測(cè)試+控制臺(tái)打印sql

單元測(cè)試

package com.ybchen.shopmanager;

import com.ybchen.shopmanager.model.BannerDO;
import com.ybchen.shopmanager.service.BannerService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

//classes=啟動(dòng)類(lèi).class
@SpringBootTest(classes = ShopManagerApplication.class)
@Slf4j
public class BannerTest {
 @Autowired
 private BannerService bannerService;

 @Test
 public void testBannerTest() {
 List<BannerDO> list = bannerService.list();
 log.info("輪播圖列表:{}", list);
 }
}

配置文件

application.properties

# 配置mybatis plus打印sql日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

測(cè)試

BaseMapperMapper

繼承該接口后,無(wú)需編寫(xiě)mapper.xml文件,即可獲得CRUD功能

/*
 * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.baomidou.mybatisplus.core.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.apache.ibatis.annotations.Param;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/*

  :`
   .:,
   :::,,.
  :: `::::::
  ::` `,:,` .:`
  `:: `::::::::.:` `:';,`
  ::::, .:::` `@++++++++:
  `` :::` @+++++++++++#
    :::, #++++++++++++++`
   ,: `::::::;'##++++++++++
   .@#@;` ::::::::::::::::::::;
   #@####@, :::::::::::::::+#;::.
   @@######+@:::::::::::::. #@:;
  , @@########':::::::::::: .#''':`
  ;##@@@+:##########@::::::::::: @#;.,:.
  #@@@######++++#####'::::::::: .##+,:#`
  @@@@@#####+++++'#####+::::::::` ,`::@#:`
  `@@@@#####++++++'#####+#':::::::::::@.
  @@@@######+++++''#######+##';::::;':,`
  @@@@#####+++++'''#######++++++++++`
  #@@#####++++++''########++++++++'
  `#@######+++++''+########+++++++;
  `@@#####+++++''##########++++++,
   @@######+++++'##########+++++#`
  @@@@#####+++++############++++;
  ;#@@@@@####++++##############+++,
  @@@@@@@@@@@###@###############++'
  @#@@@@@@@@@@@@###################+:
 `@#@@@@@@@@@@@@@@###################'`
 :@#@@@@@@@@@@@@@@@@@##################,
 ,@@@@@@@@@@@@@@@@@@@@################;
 ,#@@@@@@@@@@@@@@@@@@@##############+`
 .#@@@@@@@@@@@@@@@@@@#############@,
  @@@@@@@@@@@@@@@@@@@###########@,
  :#@@@@@@@@@@@@@@@@##########@,
  `##@@@@@@@@@@@@@@@########+,
  `+@@@@@@@@@@@@@@@#####@:`
  `:@@@@@@@@@@@@@@##@;.
   `,'@@@@##@@@+;,`
   ``...``

 _ _ /_ _ _/_. ____ / _
/ / //_//_//_|/ /_\ /_///_/_\ Talk is cheap. Show me the code.
 _/  /
 */

/**
 * Mapper 繼承該接口后,無(wú)需編寫(xiě) mapper.xml 文件,即可獲得CRUD功能
 * <p>這個(gè) Mapper 支持 id 泛型</p>
 *
 * @author hubin
 * @since 2016-01-23
 */
public interface BaseMapper<T> extends Mapper<T> {

 /**
 * 插入一條記錄
 *
 * @param entity 實(shí)體對(duì)象
 */
 int insert(T entity);

 /**
 * 根據(jù) ID 刪除
 *
 * @param id 主鍵ID
 */
 int deleteById(Serializable id);

 /**
 * 根據(jù) columnMap 條件,刪除記錄
 *
 * @param columnMap 表字段 map 對(duì)象
 */
 int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

 /**
 * 根據(jù) entity 條件,刪除記錄
 *
 * @param wrapper 實(shí)體對(duì)象封裝操作類(lèi)(可以為 null)
 */
 int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);

 /**
 * 刪除(根據(jù)ID 批量刪除)
 *
 * @param idList 主鍵ID列表(不能為 null 以及 empty)
 */
 int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

 /**
 * 根據(jù) ID 修改
 *
 * @param entity 實(shí)體對(duì)象
 */
 int updateById(@Param(Constants.ENTITY) T entity);

 /**
 * 根據(jù) whereEntity 條件,更新記錄
 *
 * @param entity 實(shí)體對(duì)象 (set 條件值,可以為 null)
 * @param updateWrapper 實(shí)體對(duì)象封裝操作類(lèi)(可以為 null,里面的 entity 用于生成 where 語(yǔ)句)
 */
 int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);

 /**
 * 根據(jù) ID 查詢
 *
 * @param id 主鍵ID
 */
 T selectById(Serializable id);

 /**
 * 查詢(根據(jù)ID 批量查詢)
 *
 * @param idList 主鍵ID列表(不能為 null 以及 empty)
 */
 List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

 /**
 * 查詢(根據(jù) columnMap 條件)
 *
 * @param columnMap 表字段 map 對(duì)象
 */
 List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

 /**
 * 根據(jù) entity 條件,查詢一條記錄
 *
 * @param queryWrapper 實(shí)體對(duì)象封裝操作類(lèi)(可以為 null)
 */
 T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

 /**
 * 根據(jù) Wrapper 條件,查詢總記錄數(shù)
 *
 * @param queryWrapper 實(shí)體對(duì)象封裝操作類(lèi)(可以為 null)
 */
 Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

 /**
 * 根據(jù) entity 條件,查詢?nèi)坑涗?
 *
 * @param queryWrapper 實(shí)體對(duì)象封裝操作類(lèi)(可以為 null)
 */
 List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

 /**
 * 根據(jù) Wrapper 條件,查詢?nèi)坑涗?
 *
 * @param queryWrapper 實(shí)體對(duì)象封裝操作類(lèi)(可以為 null)
 */
 List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

 /**
 * 根據(jù) Wrapper 條件,查詢?nèi)坑涗?
 * <p>注意: 只返回第一個(gè)字段的值</p>
 *
 * @param queryWrapper 實(shí)體對(duì)象封裝操作類(lèi)(可以為 null)
 */
 List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

 /**
 * 根據(jù) entity 條件,查詢?nèi)坑涗洠ú⒎?yè))
 *
 * @param page  分頁(yè)查詢條件(可以為 RowBounds.DEFAULT)
 * @param queryWrapper 實(shí)體對(duì)象封裝操作類(lèi)(可以為 null)
 */
 <E extends IPage<T>> E selectPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

 /**
 * 根據(jù) Wrapper 條件,查詢?nèi)坑涗洠ú⒎?yè))
 *
 * @param page  分頁(yè)查詢條件
 * @param queryWrapper 實(shí)體對(duì)象封裝操作類(lèi)
 */
 <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}

 Mybatis plus常用注解#

  • @TableName:用于定義表名
  • @TableId:用于定義表的主鍵

value:用于定義主鍵字段名
type:用于定義主鍵類(lèi)型(主鍵策略 IdType)
IdType.AUTO:主鍵自增,系統(tǒng)分配,不需要手動(dòng)輸入
IdType.NODE:未設(shè)置主鍵
IdType.INPUT:需要自己輸入主鍵值
IdType.ASSIGN_ID:系統(tǒng)分配ID,用于數(shù)值型數(shù)據(jù)(Long,對(duì)應(yīng)mysql中的BIGINT類(lèi)型)
IdType.ASSIGN_UUID:系統(tǒng)分配uuid,用于字符串型數(shù)據(jù)
TableField:用于定義表的非主鍵字段
value:用于定義非主鍵字段名,用于別名匹配,假如java對(duì)象和數(shù)據(jù)庫(kù)屬性不一樣
exist:用于指明是否為數(shù)據(jù)表的字段,true表示是,false為不是
fill:用于指定字段填充策略,一般用于填充:創(chuàng)建時(shí)間、修改時(shí)間等字段
FieldFill.DEFAULT:默認(rèn)不填充
FieldFill.INSERT:插入時(shí)填充
FieldFill.UPDATE:更新時(shí)填充
FieldFill.INSERT_UPDATE:插入、更新時(shí)填充
QueryWrapper/LambdaQueryWrapper#
  可以封裝sql對(duì)象,包括where條件,order by排序

eq:等于
ne:不等于
gt:大于
ge:大于等于
lt:小于
le:小于等于
or:拼接or
between:兩個(gè)值中間
notBetween:不在兩個(gè)值中間
like:模糊匹配
notLike:不像
likeLeft:左匹配
likeRight:右邊匹配
isNull:字段為空
in:in查詢
groupBy:分組
orderByAsc:升序
orderByDesc:降序
having:having查詢
分頁(yè)插件#
配置類(lèi)#

package com.ybchen.shopmanager.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description:分頁(yè)插件配置
 * @Author:chenyanbin
 * @Date:2021/3/5 下午10:32
 * @Versiion:1.0
 */
@Configuration
public class MybatisPlusPageConfig {

 /**
 * 舊版本
 */
// @Bean
// public PaginationInterceptor paginationInterceptor() {
// PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// return paginationInterceptor;
// }

 /**
 * 新的分頁(yè)插件,一級(jí)和二級(jí)緩存遵循mybatis的規(guī)則
 * 需要設(shè)置 MybatisConfiguration#useDeprecatedExecutor=false 避免緩存出現(xiàn)問(wèn)題
 */
 @Bean
 public MybatisPlusInterceptor mybatisPlusInterceptor() {
 MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
 mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
 return mybatisPlusInterceptor;
 }
}

演示類(lèi)

自定義xml的sql腳本

新建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">
<!--這個(gè)名稱(chēng)空間是Mapper接口的路徑-->
<mapper namespace="com.ybchen.shopmanager.mapper.BannerMapper">
 <select id="getList" resultType="com.ybchen.shopmanager.model.BannerDO">
 select * from banner
 </select>
</mapper>

BannerMapper.java添加方法

package com.ybchen.shopmanager.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ybchen.shopmanager.model.BannerDO;

import java.util.List;

/**
 * @Description:輪播圖Mapper
 * @Author:chenyanbin
 * @Date:2021/3/4 下午11:03
 * @Versiion:1.0
 */
public interface BannerMapper extends BaseMapper<BannerDO> {
 List<BannerDO> getList();
}

配置文件告訴mapper.xml路徑

application.properties

# 默認(rèn)配置路徑
mybatis-plus.mapper-locations=classpath*:/mapper/*Mapper.xml

全局配置文件

注意config-location和configuration不能同時(shí)出現(xiàn)

修改配置文件

application.properties

#配置全局配置文件?。。。?
mybatis-plus.config-location = classpath:mybatis-config.xml

新建mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
 <settings>
 <!--控制臺(tái)輸出日志-->
 <setting name="logImpl" value="STDOUT_LOGGING"/>
 </settings>
</configuration>

測(cè)試

配置實(shí)體類(lèi)別名

修改application.properties

# 配置實(shí)體類(lèi)別名
mybatis-plus.type-aliases-package=com.ybchen.shopmanager.model

測(cè)試

mybatis plus下劃線轉(zhuǎn)駝峰

默認(rèn)就是true

修改application.properties

# mybatis plus下劃線轉(zhuǎn)駝峰
mybatis-plus.configuration.map-underscore-to-camel-case=true

配置全局默認(rèn)主鍵類(lèi)型

實(shí)體類(lèi)上就不用加 @TableId(value="id",type=IdType.AUTO)

修改application.properties

# 配置全局默認(rèn)主鍵規(guī)則
mybatis-plus.global-config.db-config.id-type=auto

完整application.properties

# 端口號(hào)
server.port=9999
#===========數(shù)據(jù)庫(kù)相關(guān)=============
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1/shop?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
# 配置mybatis plus打印sql日志
#mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# 默認(rèn)配置路徑
mybatis-plus.mapper-locations=classpath*:/mapper/*Mapper.xml
#配置全局配置文件?。。?!
mybatis-plus.config-location = classpath:mybatis-config.xml
# 配置實(shí)體類(lèi)別名
mybatis-plus.type-aliases-package=com.ybchen.shopmanager.model
# mybatis plus下劃線轉(zhuǎn)駝峰
mybatis-plus.configuration.map-underscore-to-camel-case=true
# 配置全局默認(rèn)主鍵規(guī)則
mybatis-plus.global-config.db-config.id-type=auto

樂(lè)觀鎖

  大多是基于數(shù)據(jù)版本(Version)記錄機(jī)制實(shí)現(xiàn)。即為數(shù)據(jù)增加一個(gè)版本標(biāo)識(shí),在基于數(shù)據(jù)庫(kù)表的版本解決方案中,一般通過(guò)為數(shù)據(jù)庫(kù)表增加一個(gè)“version”字段來(lái)實(shí)現(xiàn)。讀取數(shù)據(jù)時(shí),將此版本號(hào)一同讀出,之后更新時(shí),對(duì)此版本號(hào)加一。此時(shí),將提交數(shù)據(jù)的版本數(shù)據(jù)與數(shù)據(jù),庫(kù)表對(duì)應(yīng)記錄的當(dāng)前版本信息進(jìn)行比較,如果提交的數(shù)據(jù),版本號(hào)大于數(shù)據(jù)庫(kù)表當(dāng)前的版本號(hào),則予以更新,否則認(rèn)為是過(guò)期數(shù)據(jù)。

實(shí)體類(lèi)增加@version

增加樂(lè)觀鎖插件

package com.ybchen.shopmanager.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description:分頁(yè)插件配置
 * @Author:chenyanbin
 * @Date:2021/3/5 下午10:32
 * @Versiion:1.0
 */
@Configuration
public class MybatisPlusPageConfig {

 /**
 * 舊版本
 */
// @Bean
// public PaginationInterceptor paginationInterceptor() {
// PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// return paginationInterceptor;
// }

 /**
 * 新的分頁(yè)插件,一級(jí)和二級(jí)緩存遵循mybatis的規(guī)則
 * 需要設(shè)置 MybatisConfiguration#useDeprecatedExecutor=false 避免緩存出現(xiàn)問(wèn)題
 */
 @Bean
 public MybatisPlusInterceptor mybatisPlusInterceptor() {
 MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
 //分頁(yè)插件
 mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
 //樂(lè)觀鎖插件
 mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
 return mybatisPlusInterceptor;
 }
}

使用

注意

  • 樂(lè)觀鎖數(shù)據(jù)類(lèi)型支持int、Integer、long、timestamp
  • 僅支持updateById和update方法

邏輯刪除

  公司在設(shè)計(jì)規(guī)范中都加入了邏輯刪除的強(qiáng)制規(guī)定,運(yùn)營(yíng)人員可以分析和審查數(shù)據(jù),也方便將數(shù)據(jù)沉淀下來(lái)用于商業(yè)分析。

  數(shù)據(jù)量過(guò)多,也會(huì)采用數(shù)據(jù)倉(cāng)庫(kù),通過(guò)監(jiān)聽(tīng)?wèi)?yīng)用數(shù)據(jù)庫(kù)的數(shù)據(jù)變化,進(jìn)行遷移到數(shù)據(jù)倉(cāng)庫(kù)。

方式一

  • 數(shù)據(jù)庫(kù)增加deleted字段,0是未刪除,1表示刪除
  • 實(shí)體類(lèi)增加屬性配置@TableLogic
  • 查詢的時(shí)候會(huì)自動(dòng)拼接上deleted=0的檢索條件

方式二

修改application.properties

# 邏輯刪除,刪除是1
mybatis-plus.global-config.db-config.logic-delete-value=1
# 邏輯刪除,未刪除是0
mybatis-plus.global-config.db-config.logic-not-delete-value=0
# 如果java實(shí)體類(lèi)沒(méi)加注解@TableLogic,則可以配置這個(gè),推薦這里配置
mybatis-plus.global-config.db-config.logic-delete-field=deleted

代碼生成器#
添加依賴(lài)#

 <!-- 代碼自動(dòng)生成依賴(lài) begin -->
 <dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-generator</artifactId>
  <version>3.4.1</version>
 </dependency>
 <!-- velocity -->
 <dependency>
  <groupId>org.apache.velocity</groupId>
  <artifactId>velocity-engine-core</artifactId>
  <version>2.0</version>
 </dependency>
 <!-- 代碼自動(dòng)生成依賴(lài) end-->

生成器類(lèi)#

package com.ybchen.shopmanager;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

/**
 * @Description:代碼生成器
 * @Author:chenyanbin
 * @Date:2021/3/6 下午5:10
 * @Versiion:1.0
 */
public class MyBatisPlusGenerator {
 public static void main(String[] args) {
 //1. 全局配置
 GlobalConfig config = new GlobalConfig();
 // 是否支持AR模式
 config.setActiveRecord(true)
  // 作者
  .setAuthor("chenyanbin")
  // 生成路徑,最好使用絕對(duì)路徑,window路徑是不一樣的
  .setOutputDir("/Users/chenyanbin/IdeaProjects/shop-manager")
  // 文件覆蓋
  .setFileOverride(true)
  // 主鍵策略
  .setIdType(IdType.AUTO)

  .setDateType(DateType.ONLY_DATE)
  // 設(shè)置生成的service接口的名字的首字母是否為I,默認(rèn)Service是以I開(kāi)頭的
  .setServiceName("%sService")

  //實(shí)體類(lèi)結(jié)尾名稱(chēng)
  .setEntityName("%sDO")

  //生成基本的resultMap
  .setBaseResultMap(true)

  //不使用AR模式
  .setActiveRecord(false)

  //生成基本的SQL片段
  .setBaseColumnList(true);

 //2. 數(shù)據(jù)源配置
 DataSourceConfig dsConfig = new DataSourceConfig();
 // 設(shè)置數(shù)據(jù)庫(kù)類(lèi)型
 dsConfig.setDbType(DbType.MYSQL)
  .setDriverName("com.mysql.cj.jdbc.Driver")
  .setUrl("jdbc:mysql://127.0.0.1:3306/shop?useSSL=false")
  .setUsername("root")
  .setPassword("root");

 //3. 策略配置globalConfiguration中
 StrategyConfig stConfig = new StrategyConfig();

 //全局大寫(xiě)命名
 stConfig.setCapitalMode(true)
  // 數(shù)據(jù)庫(kù)表映射到實(shí)體的命名策略
  .setNaming(NamingStrategy.underline_to_camel)

  //使用lombok
  .setEntityLombokModel(true)

  //使用restcontroller注解
  .setRestControllerStyle(true)

  // 生成的表, 支持多表一起生成,以數(shù)組形式填寫(xiě)
  .setInclude("product","banner","address","coupon","product_order");

 //4. 包名策略配置
 PackageConfig pkConfig = new PackageConfig();
 pkConfig.setParent("net.mybatisplus")
  .setMapper("mapper")
  .setService("service")
  .setController("controller")
  .setEntity("model")
  .setXml("mapper");

 //5. 整合配置
 AutoGenerator ag = new AutoGenerator();
 ag.setGlobalConfig(config)
  .setDataSource(dsConfig)
  .setStrategy(stConfig)
  .setPackageInfo(pkConfig);

 //6. 執(zhí)行操作
 ag.execute();
 System.out.println("======= 代碼生成完畢 ========");
 }
}

使用#

SpringBoot整合Swagger 3.x

添加依賴(lài)

 <!--springBoot整合swagger3.0-->
 <dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-boot-starter</artifactId>
  <version>3.0.0</version>
 </dependency>

修改application.properties

添加如下信息

spring.application.name=shop-manager
# ===== 自定義swagger配置 ===== #
swagger.enable=true
swagger.application-name= ${spring.application.name}
swagger.application-version=1.0
swagger.application-description=shop api

配置類(lèi)

package com.ybchen.shopmanager.config;

import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * @Description:swagger配置類(lèi)
 * @Author:chenyanbin
 * @Date:2021/3/5 下午10:32
 * @Versiion:1.0
 */
@Component
@Data
@ConfigurationProperties("swagger")
@EnableOpenApi
public class SwaggerConfiguration {


 /**
 * 是否開(kāi)啟swagger,生產(chǎn)環(huán)境一般關(guān)閉,所以這里定義一個(gè)變量
 */
 private Boolean enable;

 /**
 * 項(xiàng)目應(yīng)用名
 */
 private String applicationName;

 /**
 * 項(xiàng)目版本信息
 */
 private String applicationVersion;

 /**
 * 項(xiàng)目描述信息
 */
 private String applicationDescription;


 @Bean
 public Docket docket(){


 return new Docket(DocumentationType.OAS_30)
  .pathMapping("/")
  // 定義是否開(kāi)啟swagger,false為關(guān)閉,可以通過(guò)變量控制,線上關(guān)閉
  .enable(enable)
  //配置api文檔元信息
  .apiInfo(apiInfo())
  // 選擇哪些接口作為swagger的doc發(fā)布
  .select()
  //apis() 控制哪些接口暴露給swagger,
  // RequestHandlerSelectors.any() 所有都暴露
  // RequestHandlerSelectors.basePackage("net.ybchen.*") 指定包位置
  // withMethodAnnotation(ApiOperation.class)標(biāo)記有這個(gè)注解 ApiOperation
  .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
  .paths(PathSelectors.any())
  .build();

 }


 private ApiInfo apiInfo() {
 return new ApiInfoBuilder()
  .title(applicationName)
  .description(applicationDescription)
  .contact(new Contact("陳彥斌", "https://www.cnblogs.com/chenyanbin/", "543210188@qq.com"))
  .version(applicationVersion)
  .build();
 }
}

啟動(dòng)測(cè)試

  訪問(wèn)地址:http://localhost:9999/swagger-ui/index.html

  注意:如果訪問(wèn)不成功,看是否攔截器攔截了相關(guān)資源?。。。?!

常用注解

@Api

用在controller類(lèi),描述API接口

@Api(tags = "用戶模塊",value = "用戶UserController")
 public class UserController {
 }

@ApiOperation#

接口配置,用在方法上,描述接口方法

@ApiOperation("分頁(yè)用戶列表")
 @GetMapping("list")
 public JsonData list(){
​
 return JsonData.buildSuccess();
 }


@ApiParam#

方法參數(shù)配置,用在入?yún)⑸厦?,描述參?shù)

 @ApiOperation("用戶登錄")
 @PostMapping("login")
 public JsonData login(
  @ApiParam(name = "phone", value = "手機(jī)號(hào)",example = "13888888888")
  @RequestParam("phone") String phone,
​
  @ApiParam(name = "pwd", value = "密碼",example = "123456")
  @RequestParam("pwd")String pwd){
​
 return JsonData.buildSuccess();
 }

@Apilgnore#
忽略此接口不生成文檔

@ApiIgnore
 @ApiOperation("刪除用戶")
 @DeleteMapping("/delete/{id}")
 public JsonData deleteById(@PathVariable int id) {
 return JsonData.buildSuccess();
 }

@ApiModel#
用于類(lèi),表示對(duì)類(lèi)進(jìn)行說(shuō)明,用于參數(shù),用實(shí)體類(lèi)接收
@ApiModelProperty#
用于方法,字段;表示對(duì)model屬性的說(shuō)明或者數(shù)據(jù)操作更改
value:字段說(shuō)明
name:重寫(xiě)屬性名稱(chēng)
dataType:重寫(xiě)屬性類(lèi)型
required:是否必填
example:舉例說(shuō)明
hidden:隱藏
@Data
@ApiModel("用戶基本信息")

public class SaveUserRequest {
​
 private int age;
​
 private String pwd;
​
 @ApiModelProperty(value ="【必填】郵箱",required = true)
 private String email;
​
 @ApiModelProperty("【必填】手機(jī)號(hào)")
 private String phone;
​
 @ApiModelProperty(value="創(chuàng)建時(shí)間")
 private Date createTime;
​
}

@ApiResponse#
描述接口響應(yīng)

@ApiOperation("用戶登錄")
 @PostMapping("login")
 @ApiResponses({
  @ApiResponse(responseCode = CodeStatus.SUCCESS, description = "保存成功"),
  @ApiResponse(responseCode = CodeStatus.FAIL, description = "保存失敗")
 })
 public JsonData login(
  @ApiParam(name = "phone", value = "手機(jī)號(hào)",example = "13888888888")
  @RequestParam("phone") String phone,
​
  @ApiParam(name = "pwd", value = "密碼",example = "123456")
  @RequestParam("pwd")String pwd){
​
 return JsonData.buildSuccess();
 }

項(xiàng)目源碼下載

鏈接: https://pan.baidu.com/s/1OaOG0xK6jl8zDweAMkggAQ 提取碼: ed54

到此這篇關(guān)于SpringBoot 開(kāi)發(fā)提速神器 Lombok+MybatisPlus+SwaggerUI的文章就介紹到這了,更多相關(guān)SpringBoot Lombok+MybatisPlus+SwaggerUI內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java讀取文件及基于正則表達(dá)式的獲取電話號(hào)碼功能詳解

    Java讀取文件及基于正則表達(dá)式的獲取電話號(hào)碼功能詳解

    這篇文章主要介紹了Java讀取文件及基于正則表達(dá)式的獲取電話號(hào)碼功能,結(jié)合實(shí)例形式詳細(xì)分析了正則匹配操作的相關(guān)語(yǔ)法及電話號(hào)碼匹配的原理與實(shí)現(xiàn)技巧,需要的朋友可以參考下
    2017-09-09
  • 認(rèn)識(shí)Java中的Stub與StubQueue

    認(rèn)識(shí)Java中的Stub與StubQueue

    StubQueue是用來(lái)保存生成的本地代碼的Stub隊(duì)列,隊(duì)列每一個(gè)元素對(duì)應(yīng)一個(gè)InterpreterCodelet對(duì)象,InterpreterCodelet對(duì)象繼承自抽象基類(lèi)Stub,下面我們介紹一下StubQueue類(lèi)及相關(guān)類(lèi)Stub、InterpreterCodelet類(lèi)和CodeletMark類(lèi)。需要的的下伙伴可以參考下面文字內(nèi)容
    2021-09-09
  • 淺析Java中的Caffeine緩存源碼

    淺析Java中的Caffeine緩存源碼

    這篇文章主要介紹了淺析Java中的Caffeine緩存源碼,Caffeine是一個(gè)Java開(kāi)發(fā)的高性能緩存庫(kù),它提供了一種簡(jiǎn)單而強(qiáng)大的方式來(lái)管理內(nèi)存中的緩存數(shù)據(jù),Caffeine的設(shè)計(jì)目標(biāo)是提供快速、高效的緩存訪問(wèn),同時(shí)保持簡(jiǎn)單易用的API,本文針對(duì)其部分源碼做出解析,需要的朋友可以參考下
    2023-10-10
  • Spring Security LDAP實(shí)現(xiàn)身份驗(yàn)證的項(xiàng)目實(shí)踐

    Spring Security LDAP實(shí)現(xiàn)身份驗(yàn)證的項(xiàng)目實(shí)踐

    在本文中,我們涵蓋了“使用 Spring Boot 的 Spring Security LDAP 身份驗(yàn)證示例”的所有理論和示例部分,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-08-08
  • SpringBoot?表單提交全局日期格式轉(zhuǎn)換器實(shí)現(xiàn)方式

    SpringBoot?表單提交全局日期格式轉(zhuǎn)換器實(shí)現(xiàn)方式

    這篇文章主要介紹了SpringBoot?表單提交全局日期格式轉(zhuǎn)換器,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-04-04
  • Java狀態(tài)機(jī)的一種優(yōu)雅寫(xiě)法分享

    Java狀態(tài)機(jī)的一種優(yōu)雅寫(xiě)法分享

    狀態(tài)機(jī)是一種數(shù)學(xué)模型,對(duì)于我們業(yè)務(wù)實(shí)現(xiàn)有很大的幫助。我們可以用非常多的方法實(shí)現(xiàn)狀態(tài)機(jī),這篇文章就來(lái)介紹一個(gè)狀態(tài)機(jī)優(yōu)雅的實(shí)現(xiàn)方法,希望對(duì)大家有所幫助
    2023-04-04
  • Prometheus 入門(mén)教程之SpringBoot 實(shí)現(xiàn)自定義指標(biāo)監(jiān)控

    Prometheus 入門(mén)教程之SpringBoot 實(shí)現(xiàn)自定義指標(biāo)監(jiān)控

    這篇文章主要介紹了Prometheus 入門(mén)教程之SpringBoot 實(shí)現(xiàn)自定義指標(biāo)監(jiān)控,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-12-12
  • java核心編程之文件過(guò)濾類(lèi)FileFilter和FilenameFilter

    java核心編程之文件過(guò)濾類(lèi)FileFilter和FilenameFilter

    這篇文章主要為大家詳細(xì)介紹了java文件過(guò)濾類(lèi)FileFilter和FilenameFilter,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-08-08
  • MybatisPlus,無(wú)XML分分鐘實(shí)現(xiàn)CRUD操作

    MybatisPlus,無(wú)XML分分鐘實(shí)現(xiàn)CRUD操作

    這篇文章主要介紹了MybatisPlus,無(wú)XML分分鐘實(shí)現(xiàn)CRUD操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-08-08
  • springboot 使用zookeeper實(shí)現(xiàn)分布式隊(duì)列的基本步驟

    springboot 使用zookeeper實(shí)現(xiàn)分布式隊(duì)列的基本步驟

    這篇文章主要介紹了springboot 使用zookeeper實(shí)現(xiàn)分布式隊(duì)列,通過(guò)ZooKeeper的協(xié)調(diào)和同步機(jī)制,多個(gè)應(yīng)用程序可以共享一個(gè)隊(duì)列,并按照先進(jìn)先出的順序處理隊(duì)列中的消息,需要的朋友可以參考下
    2023-08-08

最新評(píng)論