SpringBoot整合MyBatisPlus代码生成器
这是生成后的包结构
先导入pom
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
</parent>
<dependencies>
<!--mybatis-plus-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.22</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
配置一下application.yml
server:
port: 80
servlet:
contest-path: /
spring:
application:
name: springboot-mybatis-plus
jackson:
#参数意义:
#JsonInclude.Include.ALWAYS 默认
#JsonInclude.Include.NON_DEFAULT 属性为默认值不序列化
#JsonInclude.Include.NON_EMPTY 属性为 空(””) 或者为 NULL 都不序列化
#JsonInclude.Include.NON_NULL 属性为NULL 不序列化
default-property-inclusion: ALWAYS
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
serialization:
WRITE_DATES_AS_TIMESTAMPS: false
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://xxxxxx/user?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: 1234
# 初始连接数
initialSize: 5
# 最小连接池数量
minIdle: 10
# 最大连接池数量
maxActive: 20
# mybatis-plus相关配置
mybatis-plus:
# xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置)
mapper-locations: classpath*:mybatis/mapper/*Mapper.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.dev.mybatisPlus.entity
# 以下配置均有默认值,可以不设置
global-config:
#刷新mapper 调试神器
refresh-mapper: true
db-config:
field-strategy: not_empty
#数据库类型
db-type: mysql
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
id-type: auto
#驼峰下划线转换
db-column-underline: true
#数据库大写下划线转换
capital-mode: true
#序列接口实现类配置
#key-generator: com.baomidou.springboot.xxx
#逻辑删除配置
#logic-delete-field: deleteFlag # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
#logic-delete-value: 1 # 逻辑已删除值(默认为 1)
#logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
#自定义填充策略接口实现
# meta-object-handler: com.zhengqing.config.MyMetaObjectHandler
#自定义SQL注入器
#sql-injector: com.baomidou.springboot.xxx
configuration:
# 是否开启自动驼峰命名规则映射:从数据库列名到Java属性驼峰命名的类似映射
map-underscore-to-camel-case: true
cache-enabled: false
# 如果查询结果中包含空值的列,则 MyBatis 在映射的时候,不会映射这个字段
# call-setters-on-nulls: true
# 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 解决oracle更新数据为null时无法转换报错,mysql不会出现此情况
jdbc-type-for-null: 'null'
创建TestGenerator类
看一下包结构
package com.zhangyu;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
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 java.util.ArrayList;
import java.util.List;
/**
* @author qiang
* @version 1.0
* @date 2021年04月26日 13:16
*/
public class TestGenerator {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/springboot-mybatis-plus/src/main/java");
gc.setFileOverride(true);
gc.setActiveRecord(true);
// XML 二级缓存
gc.setEnableCache(false);
// XML ResultMap
gc.setBaseResultMap(true);
// XML columList
gc.setBaseColumnList(true);
gc.setOpen(false);
gc.setSwagger2(true);
gc.setAuthor("zhangyu");
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
// 这里以mysql为例
dsc.setDbType( DbType.MYSQL);
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUrl("jdbc:mysql://xxx.xxx.xxx.xxx:3307/user?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false");
dsc.setUsername("root");
dsc.setPassword("123");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.zhangyu")
.setController( "controller")
.setEntity( "entity" )
.setService("service")
.setServiceImpl("service.impl")
.setMapper("mapper");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/vm/ServiceImpl.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/springboot-mybatis-plus/src/main/java/com/zhangyu/service/impl/"
+ tableInfo.getEntityName() + "ServiceImpl" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/vm/Mapper.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/springboot-mybatis-plus/src/main/java/com/zhangyu/mapper/"
+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/vm/Service.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/springboot-mybatis-plus/src/main/java/com/zhangyu/service/"
+ tableInfo.getEntityName() + "Service" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/vm/controller.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/springboot-mybatis-plus/src/main/java/com/zhangyu/controller/"
+ tableInfo.getEntityName() + "Controller" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/vm/entity.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/springboot-mybatis-plus/src/main/java/com/zhangyu/entity/"
+ tableInfo.getEntityName() + StringPool.DOT_JAVA;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
//templateConfig.setXml("\\templates\\vm\\mapper.xml");
templateConfig.setXml(null);
templateConfig.setMapper("/templates/vm/Mapper.java.vm");
templateConfig.setService("/templates/vm/Service.java.vm");
templateConfig.setServiceImpl("/templates/vm/ServiceImpl.java.vm");
templateConfig.setController("/templates/vm/controller.java");
templateConfig.setEntity("/templates/vm/entity.java");
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
//此处可以修改为您的表前缀
strategy.setTablePrefix("tb_");
// 表名生成策略
strategy.setNaming(NamingStrategy.underline_to_camel);
// 需要生成的表
strategy.setInclude(new String[] { "tb_admin" });
// 排除生成的表
//strategy.setExclude(new String[]{"test"});
//strategy.setSuperControllerClass("com.dev.mybatisPlus.controller.BaseController");
strategy.setEntityLombokModel( true );
mpg.setStrategy(strategy);
// 执行生成
mpg.execute();
}
}
介绍几个重要的配置
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.zhangyu")
.setController( "controller")
.setEntity( "entity" )
.setService("service")
.setServiceImpl("service.impl")
.setMapper("mapper");
mpg.setPackageInfo(pc);
要生成的包目录entity有的叫pojo
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
templateConfig.setMapper("/templates/vm/Mapper.java.vm");
templateConfig.setService("/templates/vm/Service.java.vm");
templateConfig.setServiceImpl("/templates/vm/ServiceImpl.java.vm");
templateConfig.setController("/templates/vm/controller.java");
templateConfig.setEntity("/templates/vm/entity.java");
mpg.setTemplate(templateConfig);
我们基于模板生成
templateConfig.setxxx mapper service都应该知道
// 策略配置
StrategyConfig strategy = new StrategyConfig();
//此处可以修改为您的表前缀
strategy.setTablePrefix("tb_");
// 表名生成策略
strategy.setNaming(NamingStrategy.underline_to_camel);
// 需要生成的表
strategy.setInclude(new String[] { "tb_admin" });
// 排除生成的表
//strategy.setExclude(new String[]{"test"});
//strategy.setSuperControllerClass("com.dev.mybatisPlus.controller.BaseController");
strategy.setEntityLombokModel( true );
mpg.setStrategy(strategy);
// 执行生成
mpg.execute();
strategy.setTablePrefix(“tb_”);作用你的数据库表如果是tb_xxx你想生成的实体类不想是Tb_xxx加上这个配
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/vm/ServiceImpl.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/springboot-mybatis-plus/src/main/java/com/zhangyu/service/impl/"
+ tableInfo.getEntityName() + "ServiceImpl" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/vm/Mapper.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/springboot-mybatis-plus/src/main/java/com/zhangyu/mapper/"
+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/vm/Service.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/springboot-mybatis-plus/src/main/java/com/zhangyu/service/"
+ tableInfo.getEntityName() + "Service" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/vm/controller.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/springboot-mybatis-plus/src/main/java/com/zhangyu/controller/"
+ tableInfo.getEntityName() + "Controller" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/vm/entity.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/springboot-mybatis-plus/src/main/java/com/zhangyu/entity/"
+ tableInfo.getEntityName() + StringPool.DOT_JAVA;
}
});
生成代码的时候根据我们自定的模板来生成文件名称
大概介绍完了开始创建自定义模板 模板包结构
第一步先创建
entity.java.vm
package ${package.Entity};
#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
import com.fasterxml.jackson.annotation.JsonFormat;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
## 表备注,作者,日期
/**
* $!{table.comment}
* @author ${author}
* @date ${date}
*/
#if(${entityLombokModel})
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
#end
#if(${superEntityClass})
public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {
#elseif(${activeRecord})
public class ${entity} extends Model<${entity}> {
#else
public class ${entity} implements Serializable {
#end
private static final long serialVersionUID = 1L;
## ---------- BEGIN 字段循环遍历 ----------
#foreach($field in ${table.fields})
#if($field.propertyType == "Integer" || $field.propertyType == "int")
#if(${field.keyFlag})
#if($field.comment == "")
/**
* ${field.name}
*/
#else
/**
* ${field.comment}
*/
#end
#if(${field.keyIdentityFlag})
@TableId(value = "${field.name}", type = IdType.AUTO)
#elseif(!$null.isNull(${idType}) && "$!idType" != "")
@TableId(value = "${field.name}", type = IdType.${idType})
#elseif(${field.convert})
@TableId("${field.name}")
#end
#else
/**
* ${field.comment}
*/
#end
#elseif($field.propertyType == "LocalDateTime")
/**
* ${field.comment}
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
#else
/**
* ${field.comment}
*/
#end
private ${field.propertyType} ${field.propertyName};
#end
#if(${activeRecord})
@Override
protected Serializable pkVal(){
#foreach($field in ${table.fields})
#if(${field.keyFlag})
return this.${field.propertyName};
#end
#end
}
#end
}
创建Mapper.java.vm
import org.apache.ibatis.annotations.Mapper;
import com.zhangyu.mappler.EasyBaseMapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import ${package.Entity}.${entity};
@Mapper
public interface ${entity}Mapper extends BaseMapper<${entity}>{
}
创建service
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.*;
import ${package.Entity}.${entity};
@Service
public interface ${entity}Service extends IService<${entity}> {
/**
* 新增 ${entity}
* @author qiang
*@date ${date}
* @param ${table.entityPath}
* @return null
*/
void insert(${entity} ${table.entityPath});
/**
* 根据id查询 ${entity}
* @author qiang
* @date ${date}
* @param id
* @return null
*/
${entity} findById(Long id);
/**
* 查询所有${entity}
* @author qiang
*@date ${date}
* @param ${table.entityPath}
* @return
*/
List<${entity}> findAll();
/**
*根据id修改${entity}
* @author qiang
* @date ${date}
* @param ${table.entityPath}
* @return null
*/
void update${entity}(${entity} ${table.entityPath});
/**
* 根据id删除${entity}
* @author qiang
* @date ${date}
* @param id
* @return null
*/
void delete(Long id);
}
创建serviceImpl
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import ${package.Mapper}.${entity}Mapper;
import java.util.List;
@Service
@Transactional
public class ${entity}ServiceImpl extends ServiceImpl<${entity}Mapper, ${entity}> implements ${entity}Service{
/**
*
* @author qiang
* @date ${date}
* @param
* @return null
*/
@Override
public void insert(${entity} ${table.entityPath}) {
this.baseMapper.insert(${table.entityPath});
}
/**
* 根据id查询
* @author qiang
* @date ${date}
* @param
* @return null
*/
@Override
public ${entity} findById(Long id) {
return baseMapper.selectById(id);
}
/**
* 修改${entity}
* @author qiang
* @date ${date}
* @param
* @return null
*/
@Override
public void update${entity}(${entity} ${table.entityPath}) {
this.baseMapper.updateById(${table.entityPath});
}
/**
*
* @author qiang
* @date ${date}
* @param
* @return null
*/
@Override
public void delete(Long userid) {
this.baseMapper.deleteById(userid);
}
/**
* @author qiang
* @date ${date}
* @param
* @return null
*/
@Override
public List<${entity}> findAll() {
return this.baseMapper.selectList(null);
}
}
创建controller.java.vm
package ${package.Controller};
#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import com.zhangyu.code.Result;
import io.swagger.annotations.*;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import org.springframework.security.access.prepost.PreAuthorize;
/**
*
* @author ${author}
* @since ${date}
*/
#if(${restControllerStyle})
@RestController
#end
@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${superControllerClass})
public class ${table.controllerName} extends ${superControllerClass} {
#else
public class ${table.controllerName} {
#end
private final Logger logger = LoggerFactory.getLogger(${table.controllerName}.class);
@Autowired
public ${table.serviceName} i${entity}Service;
/**
*
* @author qiang
* @date ${date}
* @param ${table.entityPath}
* @return null
*/
@ApiOperation(value = "新增系统${entity}", notes = "新增系统${entity}")
@PreAuthorize("hasAuthority('${table.entityPath}')" )
@PostMapping
public Mono<Result> ${table.entityPath}Add(@RequestBody ${entity} ${table.entityPath} ){
try {
i${entity}Service.insert(${table.entityPath});
return Mono.just(new Result().success());
} catch (Exception e) {
e.printStackTrace();
}
return Mono.just(new Result().failure());
}
/**
*
* @author qiang
* @date ${date}
* @param id
* @return null
*/
@ApiOperation(value = "通过id查询${entity}", notes = "通过id查询${entity}")
@PreAuthorize("hasAuthority('${table.entityPath}')")
@GetMapping("/{id}" )
public Mono<Result> findById(@PathVariable("id")Long id ){
${entity} ${table.entityPath}= i${entity}Service.findById(id);
if (${table.entityPath}==null){
return Mono.just(new Result().failure());
}
return Mono.just(new Result().success(${table.entityPath}));
}
/**
*
* @author qiang
* @date ${date}
* @param
* @return null
*/
@ApiOperation(value = "查询所有${entity}", notes = "查询所有${entity}")
@PreAuthorize("hasAuthority('${table.entityPath}')" )
@GetMapping
public Mono<Result> findAll(){
return Mono.just(new Result().success( i${entity}Service.findAll()));
}
/**
*
* @author qiang
* @date ${date}
* @param ${table.entityPath}
* @return null
*/
@ApiOperation(value = "修改${entity}", notes = "修改${entity}")
@PreAuthorize("hasAuthority('${table.entityPath}')" )
@PutMapping
public Mono<Result> updateUser(@RequestBody ${entity} ${table.entityPath}){
try{
i${entity}Service.update${entity}(${table.entityPath});
return Mono.just(new Result().success());
}catch(Exception e){
return Mono.just(new Result().failure());
}
}
/**
* 通过id删除${entity}
* @date ${date}
* @param ${table.entityPath}
* @return
*/
@ApiOperation(value = "通过id删除${entity}", notes = "通过id删除${entity}")
@PreAuthorize("hasAuthority('${table.entityPath}')" )
@DeleteMapping("delete")
public Mono<Result> delete(@RequestBody ${entity} ${table.entityPath}) {
try {
i${entity}Service.delete(${table.entityPath}.getId());
return Mono.just(new Result().success());
} catch (Exception e) {
return Mono.just(new Result().failure());
}
}
/**
* 通过id批量删除
* @author qiang
* @date ${date}
* @param ids
* @return null
*/
@ApiOperation(value = "通过id批量删除${entity}", notes = "通过id批量删除${entity}")
@PreAuthorize("hasAuthority('${table.entityPath}')" )
@DeleteMapping("/ids" )
public Mono<Result> removeByIds(@RequestBody Long ids[]){
try {
i${entity}Service.removeByIds(Arrays.asList(ids));
return Mono.just(new Result().success());
} catch (Exception e) {
return Mono.just(new Result().failure());
}
}
}
Mono<Result> Result是我自定义的消息同意返回类 可以换成自己的 但是import com.zhangyu.code.Result;要删掉换成你的
我不想换的我的也发给大家
创建ResultCode 枚举类型
/**
* @author qiang
* @version 1.0
* @date 2021/2/26 18:18
*/
public enum ResultCode {
SUCCESS(200,"成功",true),
SUCCESS_LOGIN(200,"登录成功",true),
SUCCESS_ADD(200,"添加成功",true),
FAILURE(500,"失败",false),
FAILURE_ADD(500,"添加失败",false),
FAILURE_CURRENT(500,"访问太快了",false),
PARAM_IS_INVALID(1001,"参数无效",false),
PARAM_IS_BLANK(1002,"参数为空",false),
PARAM_TYPE_BIND_ERROR(1003,"“参数类型错误",false),
PARAM_NOT_COMPLETE(1004,"参数缺失",false),
Admin_NOT_LOGGED_IN(2001,"用户未登录,访问的路径需要验证,请登录",false),
USER_LOGIN_ERROR(2002,"账号不存在或密码错误",false),
USER_ACCOUNT_FORBIDDEN(2003,"账号已被禁用",false),
USER_NOT_EXIST(2004,"用户不存在",false),
USER_HAS_EXISTED(2005,"用户已存在",false);
private Integer code;
private String message;
private Boolean flag;
ResultCode(Integer code, String message,Boolean flag) {
this.code = code;
this.message = message;
this.flag = flag;
}
private Integer code(){
return this.code;
}
private String message(){
return this.message;
}
private Boolean flag(){
return this.flag;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
}
创建Result
import lombok.Data;
import java.io.Serializable;
/**
* @author qiang
* @version 1.0
* @date 2021/2/26 21:08
*/
@Data
public class Result<T> implements Serializable {
/**
* @Fields code : 返回状态码
*/
private Integer code;
/**
* @Fields msg : 返回消息描述
*/
private String message;
/**
* @Fields data : 返回实体数据
*/
private Object data;
private Boolean flag;
public Result(Integer code, String message,Boolean flag,Object data) {
this.code = code;
this.message = message;
this.flag = flag;
this.data = data;
}
public Result(Integer code, String message,Boolean flag) {
this.code = code;
this.message = message;
this.flag = flag;
}
public Result() {
}
/**
* 成功
* @author qiang
* @date 2021/5/18 15:45
* @return com.zhangyu.code.Result
*/
public static Result success(){
Result result=new Result(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getFlag());
return result;
}
public static Result success(Object data){
Result result=new Result(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getFlag(),data);
return result;
}
public static Result success(String message, Object data){
Result result=new Result(ResultCode.SUCCESS.getCode(),message, ResultCode.SUCCESS.getFlag(),data);
return result;
}
/**
* 自定义返回信息
* @author qiang
* @date 2021/5/18 15:45
* @param code
* @param message
* @param flag
* @param data
* @return com.zhangyu.code.Result
*/
public static Result success(Integer code, String message, Boolean flag, Object data){
return new Result(code,message,false,data);
}
public static Result success(Integer code, String message, Boolean flag){
return new Result(code,message,false);
}
/**
* 默认返回失败
* @author qiang
* @date 2021/5/18 15:46
* @return com.zhangyu.code.Result
*/
public static Result failure(){
return new Result(ResultCode.FAILURE.getCode(), ResultCode.FAILURE.getMessage(), ResultCode.FAILURE.getFlag());
}
/**
* 自定义返回信息
* @author qiang
* @date 2021/5/18 15:46
* @param code
* @param message
* @param flag
* @return com.zhangyu.code.Result
*/
public static Result failure(Integer code, String message, Boolean flag){
return new Result(code,message,flag,null);
}
}
最后运行main方法就能生成了
看一下效果把