本文主要是介绍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
2.配置
3.查看生成代码
4.对代码做一处调整
Controller的 Result替换为自己封装的响应
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 + 分页封装的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!