• 基于EasyCode定制Mybatisplus全自动单表实现:新增/批量新增/修改/批量删除/分页查询/ID查询


    基于EasyCode定制Mybatisplus全自动单表实现CRUD接口

    • 分页查询
    • ID查询
    • 新增
    • 批量新增
    • 修改
    • 批量删除

    注意使用了MybatisPlus的自动填充功能,和insertBatchSomeColumn扩展批量插入功能,分页插件

    需要几个增加插件实现类

    自动填充

    package com.gton.config.autofull;
    
    import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.ibatis.reflection.MetaObject;
    import org.springframework.stereotype.Component;
    
    import java.time.LocalDateTime;
    
    /**
     * @description: Mybatis -plus  自动填充
     * @author: GuoTong
     * @createTime: 2021-10-05 18:12
     * @since JDK 1.8 OR 11
     **/
    @Slf4j
    @Component
    public class MyMetaObjectHandler implements MetaObjectHandler {
    
        @Override
        public void insertFill(MetaObject metaObject) {
            log.info("start insert fill ....");
            // 或者
            this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class); // 起始版本 3.3.3(推荐)
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class); // 起始版本 3.3.3(推荐)
        }
    
        @Override
        public void updateFill(MetaObject metaObject) {
            log.info("start update fill ....");
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class); // 起始版本 3.3.3(推荐)
    
        }
    }
    
    

    分页插件

    
        /**
         * Description:  新的分页插件
         *
         * @author: GuoTong
         */
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            // 向Mybatis过滤器链中添加分页拦截器
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
            // 添加乐观锁插件
            interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
            return interceptor;
        }
    

    自定义扩展批量插入

    package com.gton.handler;
    
    import com.baomidou.mybatisplus.annotation.FieldFill;
    import com.baomidou.mybatisplus.core.injector.AbstractMethod;
    import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
    import com.baomidou.mybatisplus.core.metadata.TableInfo;
    import com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn;
    
    import java.util.List;
    
    /**
     * @description: MyBatis-Plus提供的InsertBatchSomeColumn方法
     * @author: GuoTong
     * @createTime: 2022-12-06 16:24
     * @since JDK 1.8 OR 11
     **/
    public class EasySqlInjector extends DefaultSqlInjector {
    
    
        @Override
        public List getMethodList(Class mapperClass, TableInfo tableInfo) {
            // 注意:此SQL注入器继承了DefaultSqlInjector(默认注入器),调用了DefaultSqlInjector的getMethodList方法,保留了mybatis-plus的自带方法
            List methodList = super.getMethodList(mapperClass, tableInfo);
            methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));
            return methodList;
        }
    
    }
    

    批量插入插件注入

     /**
         * Description: 批量插入优化
         *
         * @author: GuoTong
         */
        @Bean
        public EasySqlInjector sqlInjector() {
            return new EasySqlInjector();
        }
    

    Controller的目标效果示例:

    package com.gton.user.controller;
    
    /**
     * (GpLogin)表控制层
     *
     * @author GT
     * @since 2022-12-06 20:13:00
     */
    @RestController
    @RequestMapping("gpLogin")
    @SwaggerScanClass
    public class GpLoginController {
        /**
         * 服务对象
         */
        @Autowired
        private GpLoginService gpLoginService;
    
        @Autowired
        private OpenFeignToCommodityServer openFeignToCommodityServer;
    
        /**
         * Description:  openfegin 调用
         *
         * @param request HttpServletRequest
         * @author: GuoTong
         * @date: 2022-12-06 16:52:18
         * @return:com.gton.io.Resp Resp
         */
        @RequestMapping(value = "/list", method = RequestMethod.GET)
        public Resp list(HttpServletRequest request) {
    
            String id = request.getParameter("id");
            if (StringUtils.isEmpty(id)) {
                id = "1598659338353319937";
            }
            Resp objectResp = openFeignToCommodityServer.selectOne(id);
            return Resp.Ok(objectResp.getData());
        }
    
        /**
         * 分页查询数据
         *
         * @param limitRequest 查询实体
         * @return 所有数据
         */
        @PostMapping("/queryLimit")
        public Resp> queryPage(@RequestBody BaseLimitRequest limitRequest) {
            // 分页查询
            IPage page = this.gpLoginService.queryLimitPage(limitRequest);
            // 封装返回结果集
            BaseLimitResponse data = BaseLimitResponse.getInstance(page.getRecords(), page.getTotal(), page.getPages(), limitRequest.getPageIndex(), limitRequest.getPageSize());
            return Resp.Ok(data);
        }
    
        /**
         * 通过主键查询单条数据
         *
         * @param id 主键
         * @return 单条数据
         */
        @GetMapping("/queryOne/{id}")
        public Resp selectOne(@PathVariable("id") Serializable id) {
            return Resp.Ok(this.gpLoginService.getById(id));
        }
    
        /**
         * 新增数据
         *
         * @param gpLogin 实体对象
         * @return 新增结果
         */
        @PostMapping("/save")
        public Resp insert(@RequestBody GpLogin gpLogin) {
            boolean save = false;
            String executeMsg = null;
            try {
                save = this.gpLoginService.save(gpLogin);
                executeMsg = "新增成功,id 是:" + gpLogin.getId();
            } catch (Exception e) {
                executeMsg = e.getMessage();
            }
            return save ? Resp.Ok(executeMsg) : Resp.error(executeMsg);
        }
    
        /**
         * 批量新增数据
         *
         * @param gpLoginList 实体对象
         * @return 新增结果
         */
        @PostMapping("/saveBatch")
        public Resp insertBatch(@RequestBody List gpLoginList) {
            Integer save = 0;
            String executeMsg = null;
            try {
                save = this.gpLoginService.saveBatchByEasyBaseMapper(gpLoginList);
                executeMsg = "新增成功=>id 是:" + Arrays.toString(gpLoginList.stream().map(GpLogin::getId).toArray());
            } catch (Exception e) {
                executeMsg = e.getMessage();
            }
            return save > 0 ? Resp.Ok(executeMsg) : Resp.error(executeMsg);
        }
    
    
        /**
         * 修改数据
         *
         * @param gpLogin 实体对象
         * @return 修改结果
         */
        @PutMapping("/update")
        public Resp update(@RequestBody GpLogin gpLogin) {
    
            boolean update = false;
            String executeMsg = null;
            try {
                update = this.gpLoginService.updateById(gpLogin);
                executeMsg = "修改成功,id 是:" + gpLogin.getId();
            } catch (Exception e) {
                executeMsg = e.getMessage();
            }
            return update ? Resp.Ok(executeMsg) : Resp.error(executeMsg);
        }
    
        /**
         * 删除数据
         *
         * @param idList 主键结合
         * @return 删除结果
         */
        @DeleteMapping("/dels")
        public Resp delete(@RequestParam("idList") List idList) {
            boolean delNumber = false;
            String executeMsg = null;
            try {
                delNumber = this.gpLoginService.removeByIds(idList);
                executeMsg = "删除成功,ids 是:" + idList;
            } catch (Exception e) {
                executeMsg = e.getMessage();
            }
            return delNumber ? Resp.Ok(executeMsg) : Resp.error(executeMsg);
        }
    }
    
    

    实际生成的代码:

    image

    首先看看EasyCode的模板

    image

    默认的Mybatisplus的模板少一个xml,我这里将其补充完整的

    我这里先将模板贴出来:

    Controller的模板:

    ##导入宏定义
    $!{define.vm}
    
    ##设置表后缀(宏定义)
    #setTableSuffix("Controller")
    
    ##保存文件(宏定义)
    #save("/controller", "Controller.java")
    
    ##包路径(宏定义)
    #setPackageSuffix("controller")
    
    ##定义服务名
    #set($serviceName = $!tool.append($!tool.firstLowerCase($!tableInfo.name), "Service"))
    
    ##定义实体对象名
    #set($entityName = $!tool.firstLowerCase($!tableInfo.name))
    
    import com.baomidou.mybatisplus.core.metadata.IPage;
    import com.gton.io.BaseLimitRequest;
    import com.gton.io.BaseLimitResponse;
    import com.gton.io.Resp;
    import $!{tableInfo.savePackageName}.entity.$!tableInfo.name;
    import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
    import org.springframework.web.bind.annotation.*;
    import com.gton.annotation.SwaggerScanClass;
    import org.springframework.beans.factory.annotation.Autowired;
    import java.util.Arrays;
    import java.io.Serializable;
    import java.util.List;
    
    ##表注释(宏定义)
    #tableComment("表控制层")
    @RestController
    @RequestMapping("$!tool.firstLowerCase($!tableInfo.name)")
    @SwaggerScanClass
    public class $!{tableName}  {
        /**
         * 服务对象
         */
        @Autowired
        private $!{tableInfo.name}Service $!{serviceName};
    
       /**
         * 分页查询数据
         *
         * @param limitRequest 查询实体
         * @return 所有数据
         */
        @PostMapping("/queryLimit")
         public Resp> queryPage(@RequestBody BaseLimitRequest<$!tableInfo.name> limitRequest) {
            // 分页查询
            IPage<$!tableInfo.name> page = this.$!{serviceName}.queryLimitPage(limitRequest);
            // 封装返回结果集
            BaseLimitResponse<$!tableInfo.name> data = BaseLimitResponse.getInstance(page.getRecords(), page.getTotal(), page.getPages(), limitRequest.getPageIndex(), limitRequest.getPageSize());
            return Resp.Ok(data);
        }
       
       /**
         * 通过主键查询单条数据
         *
         * @param id 主键
         * @return 单条数据
         */
        @GetMapping("/queryOne/{id}")
        public Resp<$!tableInfo.name> selectOne(@PathVariable("id") Serializable id) {
             return Resp.Ok(this.$!{serviceName}.getById(id));
        }
    
       /**
         * 新增数据
         *
         * @param $!entityName 实体对象
         * @return 新增结果
         */
        @PostMapping("/save")
        public Resp insert(@RequestBody $!tableInfo.name $!entityName) {
            boolean save = false;
            String executeMsg = null;
            try {
                save = this.$!{serviceName}.save($!entityName);
                executeMsg = "新增成功,id 是:" + $!{entityName}.getId();
            } catch (Exception e) {
                executeMsg = e.getMessage();
            }
            return save ? Resp.Ok(executeMsg) : Resp.error(executeMsg);
        }
        
         /**
         * 批量新增数据
         *
         * @param $!{entityName}List 实体对象
         * @return 新增结果
         */
        @PostMapping("/saveBatch")
        public Resp insertBatch(@RequestBody List<$!tableInfo.name> $!{entityName}List) {
            Integer save = 0;
            String executeMsg = null;
            try {
                save = this.$!{serviceName}.saveBatchByEasyBaseMapper($!{entityName}List);
                executeMsg = "新增成功=>id 是:" + Arrays.toString($!{entityName}List.stream().map($!{tableInfo.name}::getId).toArray());
            } catch (Exception e) {
                executeMsg = e.getMessage();
            }
            return save > 0 ? Resp.Ok(executeMsg) : Resp.error(executeMsg);
        }
    
    
        /**
         * 修改数据
         *
         * @param $!entityName 实体对象
         * @return 修改结果
         */
        @PutMapping("/update")
        public Resp update(@RequestBody $!tableInfo.name $!entityName) {
    
            boolean update = false;
            String executeMsg = null;
            try {
                update = this.$!{serviceName}.updateById($!entityName);
                executeMsg = "修改成功,id 是:" + $!{entityName}.getId();
            } catch (Exception e) {
                executeMsg = e.getMessage();
            }
            return update ? Resp.Ok(executeMsg) : Resp.error(executeMsg);
        }
    
        /**
         * 删除数据
         *
         * @param idList 主键结合
         * @return 删除结果
         */
        @DeleteMapping("/dels")
        public Resp delete(@RequestParam("idList") List idList) {
            boolean delNumber = false;
            String executeMsg = null;
            try {
                delNumber = this.$!{serviceName}.removeByIds(idList);
                executeMsg = "删除成功,ids 是:" + idList;
            } catch (Exception e) {
                executeMsg = e.getMessage();
            }
            return delNumber ? Resp.Ok(executeMsg) : Resp.error(executeMsg);
        }
    }
    
    

    实体类模板

    ##导入宏定义
    $!{define.vm}
    
    ##保存文件(宏定义)
    #save("/entity", ".java")
    
    ##包路径(宏定义)
    #setPackageSuffix("entity")
    
    ##自动导入包(全局变量)
    $!{autoImport.vm}
    import com.baomidou.mybatisplus.annotation.FieldFill;
    import com.baomidou.mybatisplus.annotation.IdType;
    import com.baomidou.mybatisplus.annotation.TableField;
    import com.baomidou.mybatisplus.annotation.TableId;
    import com.fasterxml.jackson.annotation.JsonFormat;
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    import lombok.Data;
    import lombok.experimental.Accessors;
    import java.io.Serializable;
    import java.time.LocalDateTime;
    
    ##表注释(宏定义)
    #tableComment("表实体类")
    @Data
    @Accessors(chain = true)
    @ApiModel(value = "$!{tableInfo.name}", description = "EasyCode")
    public class $!{tableInfo.name} implements Serializable {
     private static final long serialVersionUID = 1L;
    #foreach($column in $tableInfo.fullColumn)
       
        #if(${column.obj.name} == "id")
        @TableId(value = "id", type = IdType.ASSIGN_ID) 
        #elseif(${column.obj.name} == "create_time")
        @TableField(value = "create_time", fill = FieldFill.INSERT)
        #elseif(${column.obj.name} == "update_time")
        @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
        #else
        @TableField(value = "${column.obj.name}")
        #end
        @ApiModelProperty("${column.comment}")
        #if($!{tool.getClsNameByFullName($column.type)} == "LocalDateTime")
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime $!{column.name};
        #else 
        private $!{tool.getClsNameByFullName($column.type)} $!{column.name};
        #end
    #end
    
    }
    
    

    Mapper模板

    ##导入宏定义
    $!{define.vm}
    
    ##设置表后缀(宏定义)
    #setTableSuffix("Mapper")
    
    ##保存文件(宏定义)
    #save("/mapper", "Mapper.java")
    
    ##包路径(宏定义)
    #setPackageSuffix("mapper")
    
    import com.gton.handler.EasyBaseMapper;
    import org.apache.ibatis.annotations.Mapper;
    import $!{tableInfo.savePackageName}.entity.$!tableInfo.name;
    
    ##表注释(宏定义)
    #tableComment("表数据库访问层")
    @Mapper
    public interface $!{tableName} extends EasyBaseMapper<$!tableInfo.name> {
    
    }
    
    

    Service接口 模板

    ##导入宏定义
    $!{define.vm}
    
    ##设置表后缀(宏定义)
    #setTableSuffix("Service")
    
    ##保存文件(宏定义)
    #save("/service", "Service.java")
    
    ##包路径(宏定义)
    #setPackageSuffix("service")
    
    import com.baomidou.mybatisplus.extension.service.IService;
    import $!{tableInfo.savePackageName}.entity.$!tableInfo.name;
    import com.baomidou.mybatisplus.core.metadata.IPage;
    import com.gton.io.BaseLimitRequest;
    import java.util.List;
    
    ##表注释(宏定义)
    #tableComment("表服务接口")
    public interface $!{tableName} extends IService<$!tableInfo.name> {
    
    /**
         * Description:  分页查询
         *
         * @param limitRequest 分页查询参数
         * @author: GuoTong
         * @date: 2022-12-02 14:57:06
         * @return:com.baomidou.mybatisplus.core.metadata.IPage
         */
        IPage<$!tableInfo.name> queryLimitPage(BaseLimitRequest<$!tableInfo.name> limitRequest);
        
        
        /**
         * Description:  批量新增
         *
         * @param entityList
         * @author: GuoTong
         * @date: 2022-12-06 19:52:00
         * @return:Integer
         */
        Integer saveBatchByEasyBaseMapper(List<$!tableInfo.name> entityList);
    }
    
    

    Service实现类模板

    ##导入宏定义
    $!{define.vm}
    
    ##设置表后缀(宏定义)
    #setTableSuffix("ServiceImpl")
    
    ##保存文件(宏定义)
    #save("/service/impl", "ServiceImpl.java")
    
    ##包路径(宏定义)
    #setPackageSuffix("service.impl")
    
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import $!{tableInfo.savePackageName}.mapper.$!{tableInfo.name}Mapper;
    import $!{tableInfo.savePackageName}.entity.$!{tableInfo.name};
    import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
    import org.springframework.stereotype.Service;
    import com.alibaba.fastjson2.JSON;
    import com.alibaba.fastjson2.JSONObject;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.core.metadata.IPage;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import com.gton.io.BaseLimitRequest;
    import org.apache.commons.lang3.StringUtils;
    import javax.annotation.Resource;
    import javax.annotation.Resource;
    import java.time.LocalDateTime;
    import java.util.Map;
    import java.util.Objects;
    import java.util.Set;
    import java.util.List;
    
    ##表注释(宏定义)
    #tableComment("表服务实现类")
    @Service("$!tool.firstLowerCase($tableInfo.name)Service")
    public class $!{tableName} extends ServiceImpl<$!{tableInfo.name}Mapper, $!{tableInfo.name}> implements $!{tableInfo.name}Service {
    
        @Resource
        private $!{tableInfo.name}Mapper $!tool.firstLowerCase($tableInfo.name)Mapper;
        
        
        /**
         * Description:  分页查询
         *
         * @param limitRequest 分页查询参数
         * @author: GuoTong
         * @date: 2022-12-02 14:57:06
         * @return:com.baomidou.mybatisplus.core.metadata.IPage
         */
        @Override
        public IPage<$!{tableInfo.name}> queryLimitPage(BaseLimitRequest<$!{tableInfo.name}> limitRequest) {
            $!{tableInfo.name} requestBody = limitRequest.getRequestBody();
            long pageIndex = limitRequest.getPageIndex();
            long pageSize = limitRequest.getPageSize();
            IPage<$!{tableInfo.name}> page = new Page<>(pageIndex, pageSize);
            QueryWrapper<$!{tableInfo.name}> queryWrapper = new QueryWrapper<>();
            byte[] bytes = JSON.toJSONBytes(requestBody);
            JSONObject thisObj = JSON.parseObject(bytes);
            Set> entries = thisObj.entrySet();
            for (Map.Entry entry : entries) {
                String key = entry.getKey();
                StringBuilder column = new StringBuilder();
                char[] chars = key.toCharArray();
                for (char aChar : chars) {
                    if (Character.isUpperCase(aChar)) {
                        column.append("_");
                    }
                    column.append(aChar);
                }
                queryWrapper.eq(getValueIsBoolean(entry.getValue()), column.toString(), entry.getValue());
            }
            LocalDateTime beginTime = limitRequest.getBeginTime();
            LocalDateTime endTime = limitRequest.getEndTime();
            queryWrapper.ge(getValueIsBoolean(beginTime), "create_time", beginTime);
            queryWrapper.le(getValueIsBoolean(endTime), "create_time", beginTime);
            return $!{tool.firstLowerCase($tableInfo.name)}Mapper.selectPage(page, queryWrapper);
        }
        
          /**
         * Description:  批量新增优化版
         *
         * @param entityList entityList
         * @author: GuoTong
         * @date: 2022-12-06 19:54:59
         * @return:java.lang.Integer
         */
        @Override
        public Integer saveBatchByEasyBaseMapper(List<$!{tableInfo.name}> entityList) {
    
            return $!{tool.firstLowerCase($tableInfo.name)}Mapper.insertBatchSomeColumn(entityList);
        }
        
        private boolean getValueIsBoolean(Object object) {
    
            if (object instanceof String) {
                return StringUtils.isNotEmpty((CharSequence) object);
            }
            return !Objects.isNull(object);
        }
    }
    
    

    Mapper模板

    ##引入mybatis支持
    $!{mybatisSupport.vm}
    
    ##设置保存名称与保存位置
    $!callback.setFileName($tool.append($!{tableInfo.name}, "Mapper.xml"))
    $!callback.setSavePath($tool.append($modulePath, "/src/main/resources/mapper"))
    
    ##拿到主键
    #if(!$tableInfo.pkColumn.isEmpty())
        #set($pk = $tableInfo.pkColumn.get(0))
    #end
    
    "1.0" encoding="UTF-8"?>
    "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    "$!{tableInfo.savePackageName}.mapper.$!{tableInfo.name}Mapper">
    
        "$!{tableInfo.savePackageName}.entity.$!{tableInfo.name}" id="$!{tableInfo.name}Map">
    #foreach($column in $tableInfo.fullColumn)
            "$!column.name" column="$!column.obj.name" jdbcType="$!column.ext.jdbcType"/>
    #end
        
    
    
    

    生成接口如下

    image

    如果你把我的方式拿过去使用,那么你肯定会报错,你还差通用请求和响应类

    package com.gton.io;
    
    import com.gton.util.ContextCommonMsg;
    import lombok.AllArgsConstructor;
    import lombok.Builder;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import lombok.experimental.Accessors;
    
    import java.io.Serializable;
    
    /**
     * @description: 通用返回对象
     * 贫血型模型
     * @author: GuoTong
     * @createTime: 2022-09-24 13:16
     * @since JDK 1.8 OR 11
     **/
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @Accessors(chain = true)
    public class Resp implements Serializable {
        //状态码
        protected String code;
    
        //提示信息
        protected String msg;
    
        //返回的数据
        protected T data;
    
    
        /**
         * Description:常用返回数据抽离
         */
        public static  Resp LoginOk() {
            return new Resp().
                    setCode(ContextCommonMsg.LOGIN_SUCCESS_CODE).
                    setMsg(ContextCommonMsg.LOGIN_SUCCESS_MSG);
        }
    
        public static  Resp LoginFail() {
            return new Resp().
                    setCode(ContextCommonMsg.LOGIN_FAIL_CODE).
                    setMsg(ContextCommonMsg.LOGIN_FAIL_MSG);
        }
    
        public static  Resp error(String errorMsg) {
            return new Resp().
                    setCode(ContextCommonMsg.FAIL_CODE).
                    setMsg(errorMsg);
        }
    
        public static  Resp error() {
            return new Resp().
                    setCode(ContextCommonMsg.FAIL_CODE).
                    setMsg(ContextCommonMsg.FAIL_MSG);
        }
    
        public static  Resp error(String errorMsg, String failCode) {
            return new Resp().
                    setCode(failCode).
                    setMsg(errorMsg);
        }
    
        public static  Resp error(String errorMsg, String failCode, T data) {
            return new Resp().
                    setCode(failCode).
                    setData(data).
                    setMsg(errorMsg);
        }
    
        public static  Resp Ok(T data) {
            return new Resp().
                    setCode(ContextCommonMsg.SUCCESS_CODE).
                    setMsg(ContextCommonMsg.SUCCESS_MSG).
                    setData(data);
        }
    
        public static  Resp Ok() {
            return new Resp().
                    setCode(ContextCommonMsg.SUCCESS_CODE).
                    setMsg(ContextCommonMsg.SUCCESS_MSG);
        }
    
        public static  Resp Ok(T data, String msg) {
            return new Resp().
                    setCode(ContextCommonMsg.SUCCESS_CODE).
                    setMsg(msg).
                    setData(data);
        }
    
        public static  Resp Ok(T data, String msg, String successCode) {
            return new Resp().
                    setCode(successCode).
                    setMsg(msg).
                    setData(data);
        }
    
    }
    
    package com.gton.io;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import java.io.Serializable;
    
    /**
     * @description: 分页参数对象
     * 贫血型模型
     * @author: GuoTong
     * @createTime: 2022-09-24 13:31
     * @since JDK 1.8 OR 11
     **/
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class BasePage implements Serializable {
    
        /**
         * Description:  当前页 || 默认是从第一页开始
         *
         * @author: GuoTong
         * @date: 2022-09-24 13:32:36
         */
        protected long pageIndex = 1;
    
    
        /**
         * Description:  每页显示条数 || 默认是每页展示10条
         *
         * @author: GuoTong
         * @date: 2022-09-24 13:32:36
         */
        protected long pageSize = 10;
    
    
        public long getPageIndex() {
            if (this.pageIndex <= 1) {
                this.pageIndex = 1;
            }
            return pageIndex;
        }
    
        public long getPageSize() {
            if (this.pageSize <= 1) {
                this.pageSize = 10;
            }
            return pageSize;
        }
    
    
    }
    
    
    package com.gton.io;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import java.util.List;
    
    /**
     * @description: 通用响应
     * @author: GuoTong
     * @createTime: 2022-12-02 14:12
     * @since JDK 1.8 OR 11
     **/
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class BaseLimitResponse extends BasePage {
    
        /**
         * Description: 当前页数据
         */
        private List responseBody;
    
        /**
         * Description:  总条数
         */
        private long totalNum;
    
    
        /**
         * Description:  总页数
         */
        private long pageCount;
    
    
        public static  BaseLimitResponse getInstance() {
            return new BaseLimitResponse<>();
        }
    
        /**
         * Description: 获取响应对象
         *
         * @param responseBody 当前页数据
         * @param totalNum     总数据
         * @param pageCount    总页数
         * @param pageIndex    当前页
         * @param pageSize     每页展示数据大小
         * @author: GuoTong
         * @date: 2022-12-02 15:01:48
         * @return:com.gton.io.BaseLimitResponse
         */
        public static  BaseLimitResponse getInstance(List responseBody, long totalNum, long pageCount, long pageIndex, long pageSize) {
            BaseLimitResponse response = new BaseLimitResponse<>();
            response.setResponseBody(responseBody);
            response.setPageCount(pageCount);
            response.setTotalNum(totalNum);
            response.setPageSize(pageSize);
            response.setPageIndex(pageIndex);
            return response;
        }
    }
    
    
    package com.gton.io;
    
    import com.fasterxml.jackson.annotation.JsonFormat;
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import org.springframework.format.annotation.DateTimeFormat;
    
    import java.time.LocalDateTime;
    
    /**
     * @description: 通用请求
     * @author: GuoTong
     * @createTime: 2022-12-02 14:09
     * @since JDK 1.8 OR 11
     **/
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class BaseLimitRequest extends BasePage {
    
        /**
         * Description: 实体类
         */
        private T requestBody;
    
    
        /**
         * Description: 开始时间
         */
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime beginTime;
    
    
        /**
         * Description: 结束时间
         */
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime endTime;
    
    }
    
    
  • 相关阅读:
    windows下 C++ 实现类属性的get和set方式
    HDFS架构
    腾讯云入选挑战者象限,2023 Gartner容器管理魔力象限发布
    2022年中级经济师《经济基础知识》考试大纲
    记录Oracle rac 19C(19.15)补丁升级(OPatch 33803476)操作过程
    渗透测试与HTTP中的PUT请求
    如何在手机或平板上编写代码?
    【C++】超详细入门——详解函数返回类型
    树莓派+墨水屏 = DIY一个超慢速电影播放器
    java计算机毕业设计二手车商城源码+mysql数据库+系统+lw文档+部署
  • 原文地址:https://www.cnblogs.com/gtnotgod/p/16960484.html