MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
MyBatis-Plus 官网:https://mp.baomidou.com
本篇文章demo:https://gitee.com/wslxm/spring-boot-mybatis-plus
-- 建测试表
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 '邮箱',
PRIMARY KEY (id)
);
-- 添加测试数据
DELETE FROM user;
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]');
主要依赖
com.baomidou
mybatis-plus-boot-starter
3.1.0
完整依赖
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.7.RELEASE
com.example
spring-boot-mybatis-plus
0.0.1-SNAPSHOT
spring-boot-mybatis-plus
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
true
mysql
mysql-connector-java
8.0.16
runtime
com.alibaba
druid-spring-boot-starter
1.1.10
com.baomidou
mybatis-plus-boot-starter
3.1.0
org.springframework.boot
spring-boot-maven-plugin
数据连接配置
server:
port: 8088
spring:
# DataSource Config
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/mybatis-plus?useUnicode=true&characterEncoding=utf-8&useTimezone=true&serverTimezone=GMT%2B8
username: root
password: 123456
mybatis-plus: 相关配置(暂时可不配置,有默认,需要时按需配置)
# mybatis-plus相关配置,
mybatis-plus:
### xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置)
mapper-locations: classpath:mapper/*.xml
### 枚举配置,支持*匹配, 多个目录用逗号分隔
type-enums-package: com.trade.api.enums
# 以下配置均有默认值,可以不设置
global-config:
db-config:
#主键类型 auto:"数据库ID自增" 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一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
#### 逻辑删除相关配置
mybatis-plus:
global-config:
db-config:
logic-delete-field: deleted #全局逻辑删除字段值 3.3.0开始支持,详情看下面。
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
@Data
@TableName(value = "user")
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
/**
* TODO 用户
*
* @date 2020/2/4 0004 14:28
* @return
*/
@Repository
public interface UserMapper extends BaseMapper {
}
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/findAll")
public List findAll() {
List users = userMapper.selectList(null);
return users;
}
}
可以测试使用了
com.baomidou
mybatis-plus-generator
3.3.1.tmp
org.apache.velocity
velocity-engine-core
2.2
org.freemarker
freemarker
2.3.29
来自官网:
修改包路径,数据库连接信息,运行即可
默认生成:
service
serviceImpl
entity
controller
mapper
mapper.xml(这个默认没内容)
package com.example.springbootmybatisplus.utils;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
/**
*
* 读取控制台内容
*
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("jobob");
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis-plus?useUnicode=true&characterEncoding=utf-8&useTimezone=true&serverTimezone=GMT%2B8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("com.example.springbootmybatisplus");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录");
return false;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
输入代码生成路径
及要生成代码对应的数据库表
如下:
生成更多可自定义模板并配置,详情看官网
BaseMapper-CRUD 和 Iservice -CRUD 的区别是后者有批量操作,api 命名有些不同
BaseMapper 官网Api文档:https://mybatis.plus/guide/crud-interface.html#mapper-crud
@SpringBootTest
@RunWith(SpringRunner.class)
public class InsertTest {
@Autowired
private UserMapper userMapper;
//添加 -- BaseMapper api不支持批量添加
@Test
public void insert() {
//当前数据库id设置为自增,id策略需设置id-type配置,参考yml配置说明
User user = new User();
user.setName("wangsong");
user.setAge(23);
user.setEmail("[email protected]");
userMapper.insert(user);
System.out.println(user.getId());
}
}
@SpringBootTest
@RunWith(SpringRunner.class)
public class DeleteTest {
// 官网api
// // 根据 entity 条件,删除记录
// int delete(@Param(Constants.WRAPPER) Wrapper wrapper);
// // 删除(根据ID 批量删除)
// int deleteBatchIds(@Param(Constants.COLLECTION) Collection extends Serializable> idList);
// // 根据 ID 删除
// int deleteById(Serializable id);
// // 根据 columnMap 条件,删除记录
// int deleteByMap(@Param(Constants.COLUMN_MAP) Map columnMap);
@Autowired
private UserMapper userMapper;
// id删除
@Test
public void deleteById() {
userMapper.deleteById(8L);
}
// ids 批量删除
@Test
public void deleteBatchIds() {
List ids = new ArrayList<>();
ids.add(7L);
ids.add(6L);
userMapper.deleteBatchIds(ids);
}
// columnMap 条件删除
@Test
public void deleteByMap() {
//kay是字段名 value是字段值
Map map = new HashMap<>();
map.put("id","6");
userMapper.deleteByMap(map);
}
// wrapper 条件删除
@Test
public void delete() {
// 拼接sql参考:DELETE FROM user WHERE (id = ? AND name = ?)
QueryWrapper wrapper = new QueryWrapper<>();
// kay是字段名 value是字段值
wrapper.eq("id",6L)
.eq("name","wangsong");
userMapper.delete(wrapper);
}
}
@SpringBootTest
@RunWith(SpringRunner.class)
public class UpdateTest {
// 官网api
// //根据 whereEntity 条件,更新记录
// int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper updateWrapper);
// //根据 ID 修改
// int updateById(@Param(Constants.ENTITY) T entity);
@Autowired
private UserMapper userMapper;
// 根据id 更新修改
@Test
public void updateById() {
User user = new User();
//需要修改的数据 Id
user.setId(9L);
//需要修改的数据
user.setName("erping");
user.setAge(23);
user.setEmail("[email protected]");
userMapper.updateById(user);
}
// 使用 updateWrapper 条件修改(2种方式任选其一)
@Test
public void update() {
//方式一
// 更新修改字段
User user = new User();
user.setEmail("[email protected]");
// 更新添加,未设置条件 sql: UPDATE user SET email=? ,设置后:UPDATE user SET email=? WHERE (id = ?)
UpdateWrapper wrapper1 = new UpdateWrapper();
wrapper1.eq("id",9);
userMapper.update(user,wrapper1);
//方式二
// UpdateWrapper wrapper2 = new UpdateWrapper();
// wrapper2.set("email","[email protected]") // 更新的内容,可往后 .set连接
// .eq("id",9); // 更新的条件,可往后 .eq 添加
// userMapper.update(null,wrapper2);
}
}
分页查询需配置分页插件–官网配置教程(3.3.0 无需配置):https://mp.baomidou.com/guide/page.html
@SpringBootTest
@RunWith(SpringRunner.class)
public class SelectTest {
// 官网api
//
// // 根据 ID 查询
// T selectById(Serializable id);
// // 根据 entity 条件,查询一条记录
// T selectOne(@Param(Constants.WRAPPER) Wrapper queryWrapper);
//
// // 查询(根据ID 批量查询)
// List selectBatchIds(@Param(Constants.COLLECTION) Collection extends Serializable> idList);
// // 根据 entity 条件,查询全部记录
// List selectList(@Param(Constants.WRAPPER) Wrapper queryWrapper);
// // 查询(根据 columnMap 条件)
// List selectByMap(@Param(Constants.COLUMN_MAP) Map columnMap);
// // 根据 Wrapper 条件,查询全部记录
// List
mybatis-plus 分页插件配置(3.3.0 无需配置)
//Spring boot方式
@EnableTransactionManagement
@Configuration
@MapperScan("com.baomidou.cloud.service.*.mapper*")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
// paginationInterceptor.setLimit(500);
// 开启 count 的 join 优化,只针对部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
}
//普通的 Wrapper
QueryChainWrapper query();
UpdateChainWrapper update();
// Lambda 的 Wrapper,不支持 Kotlin
LambdaQueryChainWrapper lambdaQuery();
LambdaUpdateChainWrapper lambdaUpdate();
// 普通Wrapper 示例: 条件eq使用数据库字段名, value为搜索/编辑条件值
query().eq("column", value).one();
update().eq("column", value).remove();
// Lambda 的 Wrapper 示例:条件eq 使用实体类字段名, value为搜索/编辑条件值
lambdaQuery().eq(Entity::getId, value).list();
lambdaUpdate().eq(Entity::getId, value).update(entity);
查询方法示例
下方方法实现动态查询,默认查询全部+分页,可带任意搜索值,
说明值 | 描叙 |
---|---|
this.getPage() | 分页对象,分页参数的封装Page |
.eq(?,?,?) | 字段值value判断,字段key,字段值value |
.eq(?,?) | 字段key,字段值value |
TradeSpu::getSpuType | 实体类字段, 自动对应数据库字段 |
spuFindDto.getSpuType() | 前台传入字段 |
item.convert() | 返回参数转VO,暂不说明 |
示例参考
@Override
public Result> findPage(SpuTypeEnum spuType, SpuStatusEnum status, SpuSpecEnum isSpec, SpuFreePostEnum isFreePost
, String id, String spuCategoryId, String shopId, String name) {
IPage tradeSpuPage = tradeSpuMapper.selectPage(this.getPage(), new LambdaQueryWrapper()
.orderByDesc(TradeSpu::getCreateTime)
.eq(spuType != null, TradeSpu::getSpuType, spuType)
.eq(status != null, TradeSpu::getStatus, status)
.eq(isSpec != null, TradeSpu::getIsSpec, isSpec)
.eq(isFreePost != null, TradeSpu::getIsFreePost, isFreePost)
.eq(StringUtils.isNotBlank(id), TradeSpu::getId, id)
.eq(StringUtils.isNotBlank(spuCategoryId), TradeSpu::getSpuCategoryId, spuCategoryId)
.eq(StringUtils.isNotBlank(shopId), TradeSpu::getShopId, shopId)
.eq(StringUtils.isNotBlank(name), TradeSpu::getName, name)
);
return success(tradeSpuPage.convert(item -> item.convert(TradeSpuVo.class)));
}
/**
* 获取分页对象
*
* @return
*/
protected Page getPage() {
// 页数
Integer cursor = this.castToInt(request.getParameter("page" ),1);
// 分页大小
Integer limit = this.castToInt(request.getParameter("size" ),20);
return new Page<>(cursor, limit);
}
/**
* TODO 默认值
* @author ws
* @mail [email protected]
*/
public static Integer castToInt(Object value, Integer defaults) {
if(value == null){
return defaults;
}else{
return Integer.parseInt(value.toString());
}
}
IService是基于 BaseMapper 的,需先添加 BaseMapper 接口
/**
* @Author: ws
* @Description: 商品规格表 Mapper 接口
* @Date: 2020-02-24
**/
@Mapper
public interface TradeSkuMapper extends BaseMapper {
}
/**
* TODO mybatis-plus-IService接口,提供批量操作,需结合 BaseMapper 使用,如: ServiceImpl
*
* @author ws
* @mail [email protected]
* @date 2020/2/25 0025 18:04
*/
@Repository
public class TradeSkuIService extends ServiceImpl {
}
@Autowired
private TradeSkuIService tradeSkuIService ;
使用:tradeSkuIService. --> crud-api
IService CRUD 批量支持API
方法 | 说明 |
---|---|
saveBatch() | 批量添加 |
saveOrUpdateBatch() | 批量修改插入 |
removeByIds() | ID批量删除 |
updateBatchById() | ID批量更新 |
listByIds() | ID批量查询 |
Mapper CRUD 批量支持API
方法 | 说明 |
---|---|
deleteBatchIds() | ID批量删除 |
selectBatchIds() | ID批量查询 |
1.1、枚举配置有什么用?
------比如数据库保存了的数据为【1, 2,3】对应,【审核,未审核,审核通过】
1.2、如何使用?
-----添加枚举类和对应配置,查询数据时自动解析成对应的枚举对象审核,返回前端为 【审核,未审核,审核通过】,前端直接展示,而不是返回【1,2,3】
1.3、前端如何传递状态参数?
-----前端直接传枚举对象,后台自动解析接收到枚举对象保存数据库时自动转为 1,2,3
1.4、注意事项?
----1、如想 前端传枚举对象 直接添加到数据库,注意勿使用注解方式
----2、如想前端直接传递中文, 直接配置@JsonValue 到desc 属性上,@JsonValue表示json序列化数据,包括返回参数和接收参数,定义与value上返回前端将为数据库值
----3、如想前端直接传递code码,请自行寻找解决办法
----4、下方只配置了Jackson,Fastjson 请看官方文档
1.5、swagger2 文档显示与实际不符,怎么办?
---- 继承ModelPropertyBuilderPlugin(实体类参数),ParameterBuilderPlugin(Parameter参数),重写并自定义追加正确的枚举信息数据当swagger2 文档上(看步骤5)
package com.trade.api.enums;
import com.baomidou.mybatisplus.core.enums.IEnum;
import lombok.Getter;
/**
* @author ws 商品类型
*/
@Getter
public enum SpuTypeEnum implements IEnum {
CATEGORY_STATUS_YES(1, "实体物品"),
CATEGORY_STATUS_NO(2, "虚拟物品"),
;
private int value;
private String desc;
SpuTypeEnum(int value, String desc) {
this.value = value;
this.desc = desc;
}
// 获取数据值-数据库值
@Override
public Integer getValue() {
return this.value;
}
// 返回前端数据-中文值
@Override
public String toString() {
return this.desc;
}
// 根据数据库值获得枚举对象
public static SpuTypeEnum getEnum(int value) {
for(SpuTypeEnum s:SpuTypeEnum.class.getEnumConstants()) {
if(s.value == value) {
return s;
}
}
return null;
}
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer(){
return builder -> builder.featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
}
private SpuTypeEnum spuType;
mybatis-plus:
### 支持 com.*.*.enums;
type-enums-package: com.trade.api.enums
SwaggerDisplayConfig 处理body 参数(post 请求传递的json数据)
SwaggerParamDisplayConfig 处理Parameter 参数(get请求传递的url参数)
Parameter
body
package com.trade.api.config;
import com.fasterxml.classmate.ResolvedType;
import com.google.common.base.Optional;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.ModelPropertyBuilder;
import springfox.documentation.schema.Annotations;
import springfox.documentation.service.AllowableListValues;
import springfox.documentation.service.AllowableValues;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;
import springfox.documentation.swagger.schema.ApiModelProperties;
import java.lang.reflect.Field;
import java.util.ArrayList;
/**
* TODO 对swagger2 字段为枚举的对象进行处理,添加枚举对象具体的描叙信息
*
* 对swagger展示进行修改 1. 数字、Boolean属性设置默认的example 2. 支持将枚举变量的描述按照枚举类定义展示
* 参考:https://juejin.im/post/5cdd60026fb9a0321f04401b 原文多数内容已经被我修改,修改为无需定义注解
*
* 判断字段类型是否为枚举,是通过反射获取枚举对象并获取相关内容,查询给字段的swagger2 的注解注释信息 description赋值
*
* @author ws
* @mail [email protected]
* @date 2020/2/28 0028 8:31
*/
@Component
@Primary
@Slf4j
public class SwaggerDisplayConfig implements ModelPropertyBuilderPlugin {
/**
* 是否允许swagger
*/
@Value("${swagger.enable:true}")
private Boolean enableSwagger;
@Override
public void apply(ModelPropertyContext context) {
//如果不支持swagger的话,直接返回
if (!enableSwagger) {
return;
}
//获取当前字段的类型
final Class fieldType = context.getBeanPropertyDefinition().get().getField().getRawType();
//设置对数字的字段设置默认的example
setDefaultExample(context, fieldType);
//为枚举字段设置注释
descForEnumFields(context, fieldType);
}
/**
* TODO
*
* @param context swagger2 注释对象
* @param fieldType fieldType 字段类型
* @return void
* @author ws
* @mail [email protected]
* @date 2020/2/28 0028 8:01
*/
private void descForEnumFields(ModelPropertyContext context, Class fieldType) {
Optional annotation = Optional.absent();
if (context.getAnnotatedElement().isPresent()) {
annotation = annotation.or(ApiModelProperties.findApiModePropertyAnnotation(context.getAnnotatedElement().get()));
}
if (context.getBeanPropertyDefinition().isPresent()) {
annotation = annotation.or(Annotations.findPropertyAnnotation(
context.getBeanPropertyDefinition().get(),
ApiModelProperty.class));
}
try {
StringBuffer displayValues = new StringBuffer();
//判断字段是否被定义为枚举
if (!fieldType.isEnum()) {
return;
}
//获得枚举并获取相关枚举对象属性
Class> aClass = Class.forName(fieldType.getName());
Enum[] enumConstants = (Enum[]) aClass.getEnumConstants();
System.out.println(enumConstants);
ArrayList enums = new ArrayList<>();
for (Enum enum1 : enumConstants) {
//得到枚举实例名,enum1.name() :枚举属性名,enum1:枚举属性数据
displayValues.append(enum1.name() + ":" + enum1 + " || ");
enums.add(enum1.name());
}
String joinText = " (" + String.join("; ", displayValues.substring(0, displayValues.length() - 2)) + ")";
// 获取当前注解对象,并赋值description参数
Field mField = ModelPropertyBuilder.class.getDeclaredField("description");
mField.setAccessible(true);
// 原注释信息 + 自定义枚举对象内容
joinText = mField.get(context.getBuilder()) + joinText;
//赋值
final ResolvedType resolvedType = context.getResolver().resolve(fieldType);
AllowableValues allowableValues = new AllowableListValues(enums, enums.size()+"");
context.getBuilder().allowableValues(allowableValues).description(joinText).type(resolvedType);
} catch (Exception e) {
log.error(e.getMessage());
}
}
/**
* 设置默认的example
*/
private void setDefaultExample(ModelPropertyContext context, Class fieldType) {
if (Number.class.isAssignableFrom(fieldType)) {
context.getBuilder().example("0");
}
if (Boolean.class.isAssignableFrom(fieldType)) {
context.getBuilder().example("true");
}
}
@Override
public boolean supports(DocumentationType documentationType) {
return true;
}
}
package com.trade.api.config;
import com.fasterxml.classmate.ResolvedType;
import com.google.common.base.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.service.AllowableListValues;
import springfox.documentation.service.AllowableValues;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.ParameterBuilderPlugin;
import springfox.documentation.spi.service.contexts.ParameterContext;
import java.util.ArrayList;
/**
* TODO 对swagger2 字段为枚举的对象进行处理,添加枚举对象具体的描叙信息
*
* 对swagger展示进行修改 1. 数字、Boolean属性设置默认的example 2. 支持将枚举变量的描述按照枚举类定义展示
* 参考:https://juejin.im/post/5cdd60026fb9a0321f04401b 原文多数内容已经被我修改,修改为无需定义注解
*
* 判断字段类型是否为枚举,是通过反射获取枚举对象并获取相关内容,查询给字段的swagger2 的注解注释信息 description赋值
*
* @author ws
* @mail [email protected]
* @date 2020/2/28 0028 8:31
*/
@SuppressWarnings("all")
@Component
@Primary
@Slf4j
public class SwaggerParamDisplayConfig implements ParameterBuilderPlugin {
/**
* 是否允许swagger
*/
@Value("${swagger.enable:true}")
private Boolean enableSwagger;
@Override
public void apply(ParameterContext context) {
//获取当前字段的类型
Optional type = context.parameterBuilder().build().getType();
String className = type.get().toString();
Class> aClass = null;
try {
aClass = Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// 为枚举字段设置注释
this.descForEnumFields(context, aClass);
}
/**
* TODO
*
* @param context swagger2 注释对象
* @param fieldType fieldType 字段类型
* @return void
* @author ws
* @mail [email protected]
* @date 2020/2/28 0028 8:01
*/
private void descForEnumFields(ParameterContext context, Class fieldType) {
//判断字段是否被定义为枚举
if (!fieldType.isEnum()) {
return;
}
try {
//获得枚举并获取相关枚举对象属性
Class> aClass = Class.forName(fieldType.getName());
Enum[] enumConstants = (Enum[]) aClass.getEnumConstants();
ArrayList enums = new ArrayList<>();
StringBuffer description = new StringBuffer();
for (Enum enum1 : enumConstants) {
//得到枚举实例名,enum1.name() :枚举属性名,enum1:枚举属性数据
description.append(enum1.name() + ":" + enum1 + " || ");
enums.add(enum1.name());
}
// 获取注释信息
String joinText = " (" + String.join("; ", description.substring(0, description.length() - 2)) + ")";
// 获取allowableValues值对象数据
AllowableValues allowableValues = new AllowableListValues(enums, enums.size() + "");
// 赋值
context.parameterBuilder().allowableValues(allowableValues).description(joinText).build();
} catch (Exception e) {
log.error(e.getMessage());
}
}
@Override
public boolean supports(DocumentationType documentationType) {
return true;
}
}
### 屏蔽swagger+ 无默认值错误日志 + nacos心跳日志
logging:
level:
io.swagger.models.parameters.AbstractSerializableParameter: error
com.alibaba.nacos.client.naming: error`’
数据库逻辑删除字段为 deleted ,下方配置为deleted (全局配置)
删除状态1,未删除状态 0,
删除状态,使用查询修改都会添加 where deleted =0
mybatis-plus:
global-config:
db-config:
logic-delete-field: deleted #全局逻辑删除字段值 3.3.0开始支持,详情看下面。
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
如无配置全局逻辑删除字段值,或者版本在 3.3.0 以下,请在实体类逻辑删除字段添加 @TableLogic 注解
如同时配置了全局逻辑删除字段和@TableLogic ,则以实体上@TableLogic为准