基于EasyCode定制Mybatisplus全自动单表实现:新增/批量新增/修改/批量删除/分页查询/ID查询
阅读原文时间:2023年07月08日阅读:3

基于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<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
        // 注意:此SQL注入器继承了DefaultSqlInjector(默认注入器),调用了DefaultSqlInjector的getMethodList方法,保留了mybatis-plus的自带方法
        List<AbstractMethod> 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();
    }


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<Object> objectResp = openFeignToCommodityServer.selectOne(id);
        return Resp.Ok(objectResp.getData());
    }

    /**
     * 分页查询数据
     *
     * @param limitRequest 查询实体
     * @return 所有数据
     */
    @PostMapping("/queryLimit")
    public Resp<BaseLimitResponse<GpLogin>> queryPage(@RequestBody BaseLimitRequest<GpLogin> limitRequest) {
        // 分页查询
        IPage<GpLogin> page = this.gpLoginService.queryLimitPage(limitRequest);
        // 封装返回结果集
        BaseLimitResponse<GpLogin> 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<GpLogin> selectOne(@PathVariable("id") Serializable id) {
        return Resp.Ok(this.gpLoginService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param gpLogin 实体对象
     * @return 新增结果
     */
    @PostMapping("/save")
    public Resp<String> 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<String> insertBatch(@RequestBody List<GpLogin> 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<String> 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<String> delete(@RequestParam("idList") List<Long> 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);
    }
}

实际生成的代码:

默认的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<BaseLimitResponse<$!tableInfo.name>> 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<String> 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<String> 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<String> 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<String> delete(@RequestParam("idList") List<Long> 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<Map.Entry<String, Object>> entries = thisObj.entrySet();
        for (Map.Entry<String, Object> 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

<?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">
<mapper namespace="$!{tableInfo.savePackageName}.mapper.$!{tableInfo.name}Mapper">

    <resultMap type="$!{tableInfo.savePackageName}.entity.$!{tableInfo.name}" id="$!{tableInfo.name}Map">
#foreach($column in $tableInfo.fullColumn)
        <result property="$!column.name" column="$!column.obj.name" jdbcType="$!column.ext.jdbcType"/>
#end
    </resultMap>

</mapper>

生成接口如下

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

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<T> implements Serializable {
    //状态码
    protected String code;

    //提示信息
    protected String msg;

    //返回的数据
    protected T data;

    /**
     * Description:常用返回数据抽离
     */
    public static <T> Resp<T> LoginOk() {
        return new Resp<T>().
                setCode(ContextCommonMsg.LOGIN_SUCCESS_CODE).
                setMsg(ContextCommonMsg.LOGIN_SUCCESS_MSG);
    }

    public static <T> Resp<T> LoginFail() {
        return new Resp<T>().
                setCode(ContextCommonMsg.LOGIN_FAIL_CODE).
                setMsg(ContextCommonMsg.LOGIN_FAIL_MSG);
    }

    public static <T> Resp<T> error(String errorMsg) {
        return new Resp<T>().
                setCode(ContextCommonMsg.FAIL_CODE).
                setMsg(errorMsg);
    }

    public static <T> Resp<T> error() {
        return new Resp<T>().
                setCode(ContextCommonMsg.FAIL_CODE).
                setMsg(ContextCommonMsg.FAIL_MSG);
    }

    public static <T> Resp<T> error(String errorMsg, String failCode) {
        return new Resp<T>().
                setCode(failCode).
                setMsg(errorMsg);
    }

    public static <T> Resp<T> error(String errorMsg, String failCode, T data) {
        return new Resp<T>().
                setCode(failCode).
                setData(data).
                setMsg(errorMsg);
    }

    public static <T> Resp<T> Ok(T data) {
        return new Resp<T>().
                setCode(ContextCommonMsg.SUCCESS_CODE).
                setMsg(ContextCommonMsg.SUCCESS_MSG).
                setData(data);
    }

    public static <T> Resp<T> Ok() {
        return new Resp<T>().
                setCode(ContextCommonMsg.SUCCESS_CODE).
                setMsg(ContextCommonMsg.SUCCESS_MSG);
    }

    public static <T> Resp<T> Ok(T data, String msg) {
        return new Resp<T>().
                setCode(ContextCommonMsg.SUCCESS_CODE).
                setMsg(msg).
                setData(data);
    }

    public static <T> Resp<T> Ok(T data, String msg, String successCode) {
        return new Resp<T>().
                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<T> extends BasePage {

    /**
     * Description: 当前页数据
     */
    private List<T> responseBody;

    /**
     * Description:  总条数
     */
    private long totalNum;

    /**
     * Description:  总页数
     */
    private long pageCount;

    public static <T> BaseLimitResponse<T> 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<T>
     */
    public static <T> BaseLimitResponse<T> getInstance(List<T> responseBody, long totalNum, long pageCount, long pageIndex, long pageSize) {
        BaseLimitResponse<T> 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<T> 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;

}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章