EasyCode实现完整CRUD + 分页封装

2024-08-31 11:12

本文主要是介绍EasyCode实现完整CRUD + 分页封装,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • 1.创建一个表sys-user
    • 2.EasyCode 模板配置
        • 1.entity.java.vm
        • 2.dao.java.vm
        • 3.mapper.xml.vm
        • 4.service.java.vm
        • 5.serviceImpl.java.vm
        • 6.controller.java.vm
        • 7.PageInfo.java.vm
        • 8.PageResult.java.vm
        • 9.SunPageHelper.java.vm
    • 3.EasyCode生成CRUD
        • 1.右键表,选择Generate Code
        • 2.配置
        • 3.查看生成代码
        • 4.对代码做一处调整
          • Controller的 Result替换为自己封装的响应
    • 4.分页封装的代码
        • 1.PageInfo.java
        • 2.PageResult.java
        • 3.SunPageHelper.java
        • 4.使用方式
          • 1.DTO实体类继承PageInfo
          • 2.具体使用
            • 1.传入pageNo和pageSize
            • 2.传入计算数量的逻辑
            • 3.传入分页查询的逻辑

1.创建一个表sys-user

-- auto-generated definition
create table sys_user
(id          bigint auto_incrementprimary key,name        varchar(16) null,age         int         null,create_by   varchar(64) null,create_time timestamp   null,update_by   varchar(64) null,update_time timestamp   null,delete_flag tinyint     null,version     int         null
)charset = utf8mb4;

2.EasyCode 模板配置

1.entity.java.vm
##引入宏定义
$!{define.vm}##设置保存名称与保存位置
$!callback.setFileName($tool.append($!{tableInfo.name}, ".java"))
$!callback.setSavePath($tool.append($tableInfo.savePath, "/entity"))##拿到主键
#if(!$tableInfo.pkColumn.isEmpty())#set($pk = $tableInfo.pkColumn.get(0))
#end#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}entity;import $!{tableInfo.savePackageName}.entity.page.PageInfo;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;/*** $!{tableInfo.comment}($!{tableInfo.name})实体类** @author $!author* @since $!time.currTime()*/
@Data
@Accessors(chain = true) // 支持链式调用
public class $!{tableInfo.name} extends PageInfo implements Serializable {private static final long serialVersionUID = 1L;#foreach($column in $tableInfo.fullColumn)#if($column.comment)/*** $column.comment*/#endprivate $!{tool.getClsNameByFullName($column.type)} $!{column.name};#end
}
2.dao.java.vm
##定义初始变量
#set($tableName = $tool.append($tableInfo.name, "Mapper"))
##设置回调
$!callback.setFileName($tool.append($tableName, ".java"))
$!callback.setSavePath($tool.append($tableInfo.savePath, "/mapper"))##拿到主键
#if(!$tableInfo.pkColumn.isEmpty())#set($pk = $tableInfo.pkColumn.get(0))
#end#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.mapper;#endimport $!{tableInfo.savePackageName}.entity.$!{tableInfo.name};
import org.apache.ibatis.annotations.Param;
import java.util.List;/*** $!{tableInfo.comment}($!{tableInfo.name})表数据库访问层** @author $!author* @since $!time.currTime()*/
public interface $!{tableName} {/*** 通过ID查询单条数据** @param $!pk.name 主键* @return 实例对象*/$!{tableInfo.name} queryById($!pk.shortType $!pk.name);/*** 分页查询** @param po* @param offset 偏移量:计算公式 (pageNo - 1) * pageSize* @param pageSize 页面大小* @return 对象列表*/List<$!{tableInfo.name}> queryPage(@Param("po") $!{tableInfo.name} po, @Param("offset") Integer offset, @Param("pageSize") Integer pageSize);/*** 根据条件查询记录** @param po* @return 对象列表*/List<$!{tableInfo.name}> queryAllByLimit(@Param("po") $!{tableInfo.name} po);/*** 统计总行数** @param po 查询条件* @return 总行数*/Integer count($!{tableInfo.name} po);/*** 新增数据** @param po 实例对象(会封装新增的id)* @return 影响行数*/int insert($!{tableInfo.name} po);/*** 批量新增数据(MyBatis原生foreach方法)** @param entities 实例对象列表(会封装新增的id)* @return 影响行数*/int insertBatch(@Param("entities") List<$!{tableInfo.name}> entities);/*** 批量新增或按主键更新数据(MyBatis原生foreach方法)** @param entities 实例对象列表* @return 影响行数* @throws org.springframework.jdbc.BadSqlGrammarException 入参是空List的时候会抛SQL语句错误的异常,请自行校验入参*/int insertOrUpdateBatch(@Param("entities") List<$!{tableInfo.name}> entities);/*** 修改数据** @param po 实例对象* @return 影响行数*/int update($!{tableInfo.name} po);/*** 通过主键删除数据** @param $!pk.name 主键* @return 影响行数*/int deleteById($!pk.shortType $!pk.name);}
3.mapper.xml.vm
##引入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"/>
#end</resultMap><!--查询单个--><select id="queryById" resultMap="$!{tableInfo.name}Map">select #allSqlColumn() from $!tableInfo.obj.namewhere $!pk.obj.name = #{$!pk.name}</select><!--分页查询指定行数据--><select id="queryPage" resultMap="$!{tableInfo.name}Map">select #allSqlColumn()from $!tableInfo.obj.name<where>
#foreach($column in $tableInfo.fullColumn)<if test="po.$!column.name != null#if($column.type.equals('java.lang.String')) and po.$!column.name != ''#end">and $!column.obj.name = #{po.$!column.name}</if>
#end</where>limit #{offset}, #{pageSize}</select><!--根据条件查询记录--><select id="queryAllByLimit" resultMap="$!{tableInfo.name}Map">select #allSqlColumn()from $!tableInfo.obj.name<where>
#foreach($column in $tableInfo.fullColumn)<if test="po.$!column.name != null#if($column.type.equals('java.lang.String')) and po.$!column.name != ''#end">and $!column.obj.name = #{po.$!column.name}</if>
#end</where></select><!--统计总行数--><select id="count" resultType="java.lang.Integer">select count(1)from $!tableInfo.obj.name<where>
#foreach($column in $tableInfo.fullColumn)<if test="$!column.name != null#if($column.type.equals('java.lang.String')) and $!column.name != ''#end">and $!column.obj.name = #{$!column.name}</if>
#end</where></select><!--新增所有列--><insert id="insert" keyProperty="$!pk.name" useGeneratedKeys="true">insert into $!{tableInfo.obj.name}(#foreach($column in $tableInfo.otherColumn)$!column.obj.name#if($foreach.hasNext), #end#end)values (#foreach($column in $tableInfo.otherColumn)#{$!{column.name}}#if($foreach.hasNext), #end#end)</insert><insert id="insertBatch" keyProperty="$!pk.name" useGeneratedKeys="true">insert into $!{tableInfo.obj.name}(#foreach($column in $tableInfo.otherColumn)$!column.obj.name#if($foreach.hasNext), #end#end)values<foreach collection="entities" item="entity" separator=","><trim prefix="(" suffix=")" suffixOverrides=",">
#foreach($column in $tableInfo.otherColumn)<choose><when test="entity.${column.name} != null">#{entity.$!{column.name}}, </when><otherwise>NULL, </otherwise></choose>
#end</trim></foreach></insert><insert id="insertOrUpdateBatch" keyProperty="$!pk.name" useGeneratedKeys="true">insert into $!{tableInfo.obj.name}(id, #foreach($column in $tableInfo.otherColumn)$!column.obj.name#if($foreach.hasNext), #end#end)values<foreach collection="entities" item="entity" separator=",">(#{entity.id}, #foreach($column in $tableInfo.otherColumn)#{entity.$!{column.name}}#if($foreach.hasNext), #end#end)</foreach>on duplicate key update
#foreach($column in $tableInfo.otherColumn)$!column.obj.name = values($!column.obj.name)#if($foreach.hasNext),#end#end</insert><!--通过主键修改数据--><update id="update">update $!{tableInfo.obj.name}<set>
#foreach($column in $tableInfo.otherColumn)<if test="$!column.name != null#if($column.type.equals('java.lang.String')) and $!column.name != ''#end">$!column.obj.name = #{$!column.name},</if>
#end</set>where $!pk.obj.name = #{$!pk.name}</update><!--通过主键删除--><delete id="deleteById">delete from $!{tableInfo.obj.name} where $!pk.obj.name = #{$!pk.name}</delete></mapper>
4.service.java.vm
##定义初始变量
#set($tableName = $tool.append($tableInfo.name, "Service"))
##设置回调
$!callback.setFileName($tool.append($tableName, ".java"))
$!callback.setSavePath($tool.append($tableInfo.savePath, "/service"))##拿到主键
#if(!$tableInfo.pkColumn.isEmpty())#set($pk = $tableInfo.pkColumn.get(0))
#end#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.service;#endimport $!{tableInfo.savePackageName}.entity.$!{tableInfo.name};
import $!{tableInfo.savePackageName}.entity.page.PageResult;
import java.util.List;/*** $!{tableInfo.comment}($!{tableInfo.name})表服务接口** @author $!author* @since $!time.currTime()*/
public interface $!{tableName} {/*** 通过ID查询单条数据** @param $!pk.name 主键* @return 实例对象*/$!{tableInfo.name} queryById($!pk.shortType $!pk.name);/*** 分页查询** @param $!tool.firstLowerCase($!{tableInfo.name}) 筛选条件* @return 查询结果*/PageResult<$!{tableInfo.name}> queryByPage($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));/*** 根据条件查询记录** @param $!tool.firstLowerCase($!{tableInfo.name}) 筛选条件* @return 查询结果*/List<$!{tableInfo.name}> queryAllByLimit($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));/*** 新增数据** @param $!tool.firstLowerCase($!{tableInfo.name}) 实例对象* @return 实例对象*/$!{tableInfo.name} insert($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));/*** 修改数据** @param $!tool.firstLowerCase($!{tableInfo.name}) 实例对象* @return 实例对象*/$!{tableInfo.name} update($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));/*** 通过主键删除数据** @param $!pk.name 主键* @return 是否成功*/boolean deleteById($!pk.shortType $!pk.name);}
5.serviceImpl.java.vm
##定义初始变量
#set($tableName = $tool.append($tableInfo.name, "ServiceImpl"))
##设置回调
$!callback.setFileName($tool.append($tableName, ".java"))
$!callback.setSavePath($tool.append($tableInfo.savePath, "/service/impl"))##拿到主键
#if(!$tableInfo.pkColumn.isEmpty())#set($pk = $tableInfo.pkColumn.get(0))
#end#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}service.impl;import $!{tableInfo.savePackageName}.entity.$!{tableInfo.name};
import $!{tableInfo.savePackageName}.mapper.$!{tableInfo.name}Mapper;
import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import $!{tableInfo.savePackageName}.entity.page.PageResult;
import $!{tableInfo.savePackageName}.entity.page.SunPageHelper;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.List;/*** $!{tableInfo.comment}($!{tableInfo.name})表服务实现类** @author $!author* @since $!time.currTime()*/
@Service("$!tool.firstLowerCase($!{tableInfo.name})Service")
public class $!{tableName} implements $!{tableInfo.name}Service {@Resourceprivate $!{tableInfo.name}Mapper $!tool.firstLowerCase($!{tableInfo.name})Mapper;/*** 通过ID查询单条数据** @param $!pk.name 主键* @return 实例对象*/@Overridepublic $!{tableInfo.name} queryById($!pk.shortType $!pk.name) {return this.$!{tool.firstLowerCase($!{tableInfo.name})}Mapper.queryById($!pk.name);}/*** 分页查询** @param $!tool.firstLowerCase($!{tableInfo.name}) 筛选条件,需要携带pageNo和pageSize以及查询条件* @return 分页结果*/@Overridepublic PageResult<$!{tableInfo.name}> queryByPage($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name})) {// 使用 SunPageHelper 执行分页操作return SunPageHelper.paginate($!{tool.firstLowerCase($!{tableInfo.name})}.getPageNo(), $!{tool.firstLowerCase($!{tableInfo.name})}.getPageSize(),() -> $!tool.firstLowerCase($!{tableInfo.name})Mapper.count($!tool.firstLowerCase($!{tableInfo.name})),(offset, size) -> $!tool.firstLowerCase($!{tableInfo.name})Mapper.queryPage($!tool.firstLowerCase($!{tableInfo.name}), offset, size));}/*** 根据条件查询记录** @param $!tool.firstLowerCase($!{tableInfo.name}) 筛选条件* @return 查询结果*/@Overridepublic List<$!{tableInfo.name}> queryAllByLimit($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name})) {return this.$!{tool.firstLowerCase($!{tableInfo.name})}Mapper.queryAllByLimit($!tool.firstLowerCase($!{tableInfo.name}));}/*** 新增数据** @param $!tool.firstLowerCase($!{tableInfo.name}) 实例对象* @return 实例对象*/@Overridepublic $!{tableInfo.name} insert($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name})) {this.$!{tool.firstLowerCase($!{tableInfo.name})}Mapper.insert($!tool.firstLowerCase($!{tableInfo.name}));return $!tool.firstLowerCase($!{tableInfo.name});}/*** 修改数据** @param $!tool.firstLowerCase($!{tableInfo.name}) 实例对象* @return 实例对象*/@Overridepublic $!{tableInfo.name} update($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name})) {this.$!{tool.firstLowerCase($!{tableInfo.name})}Mapper.update($!tool.firstLowerCase($!{tableInfo.name}));return this.queryById($!{tool.firstLowerCase($!{tableInfo.name})}.get$!tool.firstUpperCase($pk.name)());}/*** 通过主键删除数据** @param $!pk.name 主键* @return 是否成功*/@Overridepublic boolean deleteById($!pk.shortType $!pk.name) {return this.$!{tool.firstLowerCase($!{tableInfo.name})}Mapper.deleteById($!pk.name) > 0;}}
6.controller.java.vm
##定义初始变量
#set($tableName = $tool.append($tableInfo.name, "Controller"))
##设置回调
$!callback.setFileName($tool.append($tableName, ".java"))
$!callback.setSavePath($tool.append($tableInfo.savePath, "/controller"))
##拿到主键
#if(!$tableInfo.pkColumn.isEmpty())#set($pk = $tableInfo.pkColumn.get(0))
#end#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.controller;#endimport $!{tableInfo.savePackageName}.entity.$!{tableInfo.name};
import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import $!{tableInfo.savePackageName}.entity.page.PageResult;
import com.sunxiansheng.response.Result;
import org.springframework.web.bind.annotation.*;import javax.annotation.Resource;
import java.util.List;/*** $!{tableInfo.comment}($!{tableInfo.name})表控制层** @author $!author* @since $!time.currTime()*/
@RestController
@RequestMapping("/$!tool.firstLowerCase($tableInfo.name)")
public class $!{tableName} {/*** 服务对象*/@Resourceprivate $!{tableInfo.name}Service $!tool.firstLowerCase($tableInfo.name)Service;/*** 通过主键查询单条数据** @param $!pk.name 主键* @return 单条数据*/@GetMapping("/{id}")public Result<$!{tableInfo.name}> queryById(@PathVariable("$!pk.name") $!pk.shortType $!pk.name) {return Result.ok(this.$!tool.firstLowerCase($tableInfo.name)Service.queryById($!pk.name));}/*** 分页查询数据** @param $!tool.firstLowerCase($tableInfo.name) 筛选条件* @return 查询结果*/@GetMapping("/queryPage")public PageResult<$!{tableInfo.name}> queryByPage(@RequestBody $!{tableInfo.name} $!tool.firstLowerCase($tableInfo.name)) {return this.$!tool.firstLowerCase($tableInfo.name)Service.queryByPage($!tool.firstLowerCase($tableInfo.name));}/*** 根据条件查询记录** @param $!tool.firstLowerCase($tableInfo.name) 筛选条件* @return 查询结果*/@GetMappingpublic Result<List<$!{tableInfo.name}>> queryAllByLimit(@RequestBody $!{tableInfo.name} $!tool.firstLowerCase($tableInfo.name)) {return Result.ok(this.$!tool.firstLowerCase($tableInfo.name)Service.queryAllByLimit($!tool.firstLowerCase($tableInfo.name)));}/*** 新增数据** @param $!tool.firstLowerCase($tableInfo.name) 实体* @return 新增结果*/@PostMappingpublic Result<$!{tableInfo.name}> add(@RequestBody $!{tableInfo.name} $!tool.firstLowerCase($tableInfo.name)) {return Result.ok(this.$!tool.firstLowerCase($tableInfo.name)Service.insert($!tool.firstLowerCase($tableInfo.name)));}/*** 编辑数据** @param $!tool.firstLowerCase($tableInfo.name) 实体* @return 编辑结果*/@PutMappingpublic Result<$!{tableInfo.name}> edit(@RequestBody $!{tableInfo.name} $!tool.firstLowerCase($tableInfo.name)) {return Result.ok(this.$!tool.firstLowerCase($tableInfo.name)Service.update($!tool.firstLowerCase($tableInfo.name)));}/*** 删除数据** @param $!pk.name 主键* @return 删除是否成功*/@DeleteMappingpublic Result<Boolean> deleteById(@RequestBody $!pk.shortType $!pk.name) {return Result.ok(this.$!tool.firstLowerCase($tableInfo.name)Service.deleteById($!pk.name));}}
7.PageInfo.java.vm
##定义初始变量
#set($className = "PageInfo")
##设置回调
$!callback.setFileName($className + ".java")
$!callback.setSavePath($tool.append($tableInfo.savePath, "/entity/page"))
##包名
#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.entity.page;#endimport java.util.Objects;/*** Description: 分页请求的入参* @Author $!author* @Create $!time.currTime()* @Version 1.1*/
public class $className {private Integer pageNo = 1;private Integer pageSize = 20;public Integer getPageNo() {return (pageNo == null || pageNo < 1) ? 1 : pageNo;}public Integer getPageSize() {return (pageSize == null || pageSize < 1) ? 20 : pageSize;}public $className setPageNo(Integer pageNo) {this.pageNo = pageNo;return this;}public $className setPageSize(Integer pageSize) {this.pageSize = pageSize;return this;}@Overridepublic int hashCode() {return Objects.hash(pageNo, pageSize);}@Overridepublic String toString() {return "$className{" +"pageNo=" + pageNo +", pageSize=" + pageSize +'}';}
}
8.PageResult.java.vm
##定义初始变量
#set($className = "PageResult")
##设置回调
$!callback.setFileName($className + ".java")
$!callback.setSavePath($tool.append($tableInfo.savePath, "/entity/page"))
##包名
#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.entity.page;#endimport java.util.Collections;
import java.util.List;import static java.util.Objects.requireNonNull;/*** Description: 分页返回的实体* @Author $!author* @Create $!time.currTime()* @Version 1.1*/
public class $className<T> {// 当前页码,默认为1private Integer pageNo = 1;// 每页显示的记录数,默认为20private Integer pageSize = 20;// 总记录条数private Integer total = 0;// 总页数private Integer totalPages = 0;// 当前页的记录列表private List<T> result = Collections.emptyList();// 表示当前页是从分页查询结果的第几条记录开始,下标从1开始private Integer start = 1;// 表示当前页是从分页查询结果的第几条记录结束,下标从1开始private Integer end = 0;// 私有构造函数,使用Builder创建实例private $className(Builder<T> builder) {this.pageNo = builder.pageNo;this.pageSize = builder.pageSize;this.total = builder.total;this.result = builder.result;calculateTotalPages();calculateStartAndEnd();}// Builder 模式实现public static class Builder<T> {private Integer pageNo = 1;private Integer pageSize = 20;private Integer total = 0;private List<T> result = Collections.emptyList();public Builder<T> pageNo(Integer pageNo) {this.pageNo = requireNonNull(pageNo, "Page number cannot be null");return this;}public Builder<T> pageSize(Integer pageSize) {this.pageSize = requireNonNull(pageSize, "Page size cannot be null");return this;}public Builder<T> total(Integer total) {this.total = requireNonNull(total, "Total count cannot be null");return this;}public Builder<T> result(List<T> result) {this.result = requireNonNull(result, "Result list cannot be null");return this;}public $className<T> build() {return new $className<>(this);}}// 计算总页数private void calculateTotalPages() {if (this.pageSize > 0) {this.totalPages = (this.total / this.pageSize) + (this.total % this.pageSize == 0 ? 0 : 1);} else {this.totalPages = 0;}}// 计算起始和结束位置private void calculateStartAndEnd() {if (this.pageSize > 0) {this.start = (this.pageNo - 1) * this.pageSize + 1;this.end = Math.min(this.pageNo * this.pageSize, this.total);} else {this.start = 1;this.end = this.total;}}// 获取当前页的起始位置public Integer getStart() {return start;}// 获取每页记录数public Integer getPageSize() {return pageSize;}// 获取当前页码public Integer getPageNo() {return pageNo;}// 获取总记录条数public Integer getTotal() {return total;}// 获取总页数public Integer getTotalPages() {return totalPages;}// 获取当前页的记录列表public List<T> getResult() {return result;}// 获取当前页的结束位置public Integer getEnd() {return end;}@Overridepublic String toString() {return "$className{" +"pageNo=" + pageNo +", pageSize=" + pageSize +", total=" + total +", totalPages=" + totalPages +", result=" + result +", start=" + start +", end=" + end +'}';}
}
9.SunPageHelper.java.vm
##定义初始变量
#set($className = "SunPageHelper")
##设置回调
$!callback.setFileName($className + ".java")
$!callback.setSavePath($tool.append($tableInfo.savePath, "/entity/page"))
##包名
#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.entity.page;#endimport java.util.List;
import java.util.function.BiFunction;
import java.util.function.Supplier;/*** Description: 分页逻辑封装* @Author $!author* @Create $!time.currTime()* @Version 1.0*/
public class $className {/*** 执行分页操作* @param pageNo 页码* @param pageSize 每页记录数* @param totalSupplier 获取总记录条数的逻辑* @param recordsSupplier 获取记录列表的逻辑* @param <T> 记录的类型* @return 分页结果*/public static <T> PageResult<T> paginate(int pageNo, int pageSize,Supplier<Integer> totalSupplier,BiFunction<Integer, Integer, List<T>> recordsSupplier) {// 计算总记录数int total;try {total = totalSupplier.get();} catch (Exception e) {throw new RuntimeException("Failed to get total count", e);}// 如果总记录数为0,返回空的 PageResultif (total == 0) {return new PageResult.Builder<T>().pageNo(pageNo).pageSize(pageSize).total(total).result(Collections.emptyList()) // 空列表.build();}// 计算 offset,表示从第几条记录开始查询int offset = calculateOffset(pageNo, pageSize);// 获取当前页的记录列表List<T> records;try {records = recordsSupplier.apply(offset, pageSize);} catch (Exception e) {throw new RuntimeException("Failed to get records", e);}// 使用 Builder 模式创建 PageResult 对象并返回return new PageResult.Builder<T>().pageNo(pageNo).pageSize(pageSize).total(total).result(records).build();}/*** 计算分页的 offset* @param pageNo 页码* @param pageSize 每页记录数* @return offset*/public static int calculateOffset(int pageNo, int pageSize) {// offset 计算公式:(当前页码 - 1) * 每页记录数return (pageNo - 1) * pageSize;}
}

3.EasyCode生成CRUD

1.右键表,选择Generate Code

CleanShot 2024-07-12 at 16.01.05@2x

2.配置

CleanShot 2024-07-16 at 14.13.08@2x

3.查看生成代码

CleanShot 2024-07-16 at 14.23.01@2x

4.对代码做一处调整
Controller的 Result替换为自己封装的响应

CleanShot 2024-07-16 at 14.16.45@2x

4.分页封装的代码

1.PageInfo.java
package com.sunxiansheng.user.entity.page;
import java.util.Objects;/*** Description: 分页请求的入参* @Author sun* @Create 2024-07-16 14:14:55* @Version 1.1*/
public class PageInfo {private Integer pageNo = 1;private Integer pageSize = 20;public Integer getPageNo() {return (pageNo == null || pageNo < 1) ? 1 : pageNo;}public Integer getPageSize() {return (pageSize == null || pageSize < 1) ? 20 : pageSize;}public PageInfo setPageNo(Integer pageNo) {this.pageNo = pageNo;return this;}public PageInfo setPageSize(Integer pageSize) {this.pageSize = pageSize;return this;}@Overridepublic int hashCode() {return Objects.hash(pageNo, pageSize);}@Overridepublic String toString() {return "PageInfo{" +"pageNo=" + pageNo +", pageSize=" + pageSize +'}';}
}
2.PageResult.java
package com.sunxiansheng.user.entity.page;
import java.util.Collections;
import java.util.List;import static java.util.Objects.requireNonNull;/*** Description: 分页返回的实体* @Author sun* @Create 2024-07-16 14:14:55* @Version 1.1*/
public class PageResult<T> {// 当前页码,默认为1private Integer pageNo = 1;// 每页显示的记录数,默认为20private Integer pageSize = 20;// 总记录条数private Integer total = 0;// 总页数private Integer totalPages = 0;// 当前页的记录列表private List<T> result = Collections.emptyList();// 表示当前页是从分页查询结果的第几条记录开始,下标从1开始private Integer start = 1;// 表示当前页是从分页查询结果的第几条记录结束,下标从1开始private Integer end = 0;// 私有构造函数,使用Builder创建实例private PageResult(Builder<T> builder) {this.pageNo = builder.pageNo;this.pageSize = builder.pageSize;this.total = builder.total;this.result = builder.result;calculateTotalPages();calculateStartAndEnd();}// Builder 模式实现public static class Builder<T> {private Integer pageNo = 1;private Integer pageSize = 20;private Integer total = 0;private List<T> result = Collections.emptyList();public Builder<T> pageNo(Integer pageNo) {this.pageNo = requireNonNull(pageNo, "Page number cannot be null");return this;}public Builder<T> pageSize(Integer pageSize) {this.pageSize = requireNonNull(pageSize, "Page size cannot be null");return this;}public Builder<T> total(Integer total) {this.total = requireNonNull(total, "Total count cannot be null");return this;}public Builder<T> result(List<T> result) {this.result = requireNonNull(result, "Result list cannot be null");return this;}public PageResult<T> build() {return new PageResult<>(this);}}// 计算总页数private void calculateTotalPages() {if (this.pageSize > 0) {this.totalPages = (this.total / this.pageSize) + (this.total % this.pageSize == 0 ? 0 : 1);} else {this.totalPages = 0;}}// 计算起始和结束位置private void calculateStartAndEnd() {if (this.pageSize > 0) {this.start = (this.pageNo - 1) * this.pageSize + 1;this.end = Math.min(this.pageNo * this.pageSize, this.total);} else {this.start = 1;this.end = this.total;}}// 获取当前页的起始位置public Integer getStart() {return start;}// 获取每页记录数public Integer getPageSize() {return pageSize;}// 获取当前页码public Integer getPageNo() {return pageNo;}// 获取总记录条数public Integer getTotal() {return total;}// 获取总页数public Integer getTotalPages() {return totalPages;}// 获取当前页的记录列表public List<T> getResult() {return result;}// 获取当前页的结束位置public Integer getEnd() {return end;}@Overridepublic String toString() {return "PageResult{" +"pageNo=" + pageNo +", pageSize=" + pageSize +", total=" + total +", totalPages=" + totalPages +", result=" + result +", start=" + start +", end=" + end +'}';}
}
3.SunPageHelper.java
package com.sunxiansheng.user.entity.page;import java.util.Collections;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Supplier;/*** Description: 分页逻辑封装* @Author sun* @Create 2024-07-16 14:14:55* @Version 1.0*/
public class SunPageHelper {/*** 执行分页操作* @param pageNo 页码* @param pageSize 每页记录数* @param totalSupplier 获取总记录条数的逻辑* @param recordsSupplier 获取记录列表的逻辑* @param <T> 记录的类型* @return 分页结果*/public static <T> PageResult<T> paginate(int pageNo, int pageSize,Supplier<Integer> totalSupplier,BiFunction<Integer, Integer, List<T>> recordsSupplier) {// 计算总记录数int total;try {total = totalSupplier.get();} catch (Exception e) {throw new RuntimeException("Failed to get total count", e);}// 如果总记录数为0,返回空的 PageResultif (total == 0) {return new PageResult.Builder<T>().pageNo(pageNo).pageSize(pageSize).total(total).result(Collections.emptyList()) // 空列表.build();}// 计算 offset,表示从第几条记录开始查询int offset = calculateOffset(pageNo, pageSize);// 获取当前页的记录列表List<T> records;try {records = recordsSupplier.apply(offset, pageSize);} catch (Exception e) {throw new RuntimeException("Failed to get records", e);}// 使用 Builder 模式创建 PageResult 对象并返回return new PageResult.Builder<T>().pageNo(pageNo).pageSize(pageSize).total(total).result(records).build();}/*** 计算分页的 offset* @param pageNo 页码* @param pageSize 每页记录数* @return offset*/public static int calculateOffset(int pageNo, int pageSize) {// offset 计算公式:(当前页码 - 1) * 每页记录数return (pageNo - 1) * pageSize;}
}
4.使用方式
1.DTO实体类继承PageInfo
2.具体使用
1.传入pageNo和pageSize
2.传入计算数量的逻辑
3.传入分页查询的逻辑
    /*** 分页查询** @param sysUser 筛选条件,需要携带pageNo和pageSize以及查询条件* @return 分页结果*/@Overridepublic PageResult<SysUser> queryByPage(SysUser sysUser) {// 使用 SunPageHelper 执行分页操作return SunPageHelper.paginate(sysUser.getPageNo(), sysUser.getPageSize(),// 查询数量() -> sysUserMapper.count(sysUser),// (offset, size) -> sysUserMapper.queryPage(sysUser, offset, size));}

这篇关于EasyCode实现完整CRUD + 分页封装的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1123742

相关文章

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

MyBatis分页查询实战案例完整流程

《MyBatis分页查询实战案例完整流程》MyBatis是一个强大的Java持久层框架,支持自定义SQL和高级映射,本案例以员工工资信息管理为例,详细讲解如何在IDEA中使用MyBatis结合Page... 目录1. MyBATis框架简介2. 分页查询原理与应用场景2.1 分页查询的基本原理2.1.1 分

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

Nginx部署HTTP/3的实现步骤

《Nginx部署HTTP/3的实现步骤》本文介绍了在Nginx中部署HTTP/3的详细步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录前提条件第一步:安装必要的依赖库第二步:获取并构建 BoringSSL第三步:获取 Nginx

MyBatis Plus实现时间字段自动填充的完整方案

《MyBatisPlus实现时间字段自动填充的完整方案》在日常开发中,我们经常需要记录数据的创建时间和更新时间,传统的做法是在每次插入或更新操作时手动设置这些时间字段,这种方式不仅繁琐,还容易遗漏,... 目录前言解决目标技术栈实现步骤1. 实体类注解配置2. 创建元数据处理器3. 服务层代码优化填充机制详

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

Java实现字节字符转bcd编码

《Java实现字节字符转bcd编码》BCD是一种将十进制数字编码为二进制的表示方式,常用于数字显示和存储,本文将介绍如何在Java中实现字节字符转BCD码的过程,需要的小伙伴可以了解下... 目录前言BCD码是什么Java实现字节转bcd编码方法补充总结前言BCD码(Binary-Coded Decima