1.创建一个表sys-user
create table sys_user
(
id bigint auto_increment
primary 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
*/#end
private $!{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;#end
import $!{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.name
where $!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;#end
import $!{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 {
@Resource
private $!{tableInfo.name}Mapper $!tool.firstLowerCase($!{tableInfo.name})Mapper;
/**
* 通过ID查询单条数据
*
* @param $!pk.name 主键
* @return 实例对象
*/
@Override
public $!{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 分页结果
*/
@Override
public 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 查询结果
*/
@Override
public 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 实例对象
*/
@Override
public $!{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 实例对象
*/
@Override
public $!{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 是否成功
*/
@Override
public 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;#end
import $!{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} {
/**
* 服务对象
*/
@Resource
private $!{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 查询结果
*/
@GetMapping
public 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 新增结果
*/
@PostMapping
public 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 编辑结果
*/
@PutMapping
public 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 删除是否成功
*/
@DeleteMapping
public 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;#end
import 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;
}
@Override
public int hashCode() {
return Objects.hash(pageNo, pageSize);
}
@Override
public 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;#end
import 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> {
// 当前页码,默认为1
private Integer pageNo = 1;
// 每页显示的记录数,默认为20
private 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;
}
@Override
public 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;#end
import 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,返回空的 PageResult
if (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](https://img-blog.csdnimg.cn/img_convert/baadcb0c10020a8fc7d1129cdbb6cb36.png)
2.配置
![CleanShot 2024-07-16 at 14.13.08@2x](https://img-blog.csdnimg.cn/img_convert/500f67fee996c76c25627b945abee10f.png)
3.查看生成代码
![CleanShot 2024-07-16 at 14.23.01@2x](https://img-blog.csdnimg.cn/img_convert/1745b066ccda77a29f7eb180c58ab837.png)
4.对代码做一处调整
Controller的 Result替换为自己封装的响应
![CleanShot 2024-07-16 at 14.16.45@2x](https://img-blog.csdnimg.cn/img_convert/47a54b791da1076e69ad709619c111c2.png)
4.分页封装的代码
1.PageInfo.java
package com.sunxiansheng.user.entity.page;
import java.util.Objects;
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;
}
@Override
public int hashCode() {
return Objects.hash(pageNo, pageSize);
}
@Override
public 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;
public class PageResult<T> {
private Integer pageNo = 1;
private Integer pageSize = 20;
private Integer total = 0;
private Integer totalPages = 0;
private List<T> result = Collections.emptyList();
private Integer start = 1;
private Integer end = 0;
private PageResult(Builder<T> builder) {
this.pageNo = builder.pageNo;
this.pageSize = builder.pageSize;
this.total = builder.total;
this.result = builder.result;
calculateTotalPages();
calculateStartAndEnd();
}
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;
}
@Override
public 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;
public class SunPageHelper {
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);
}
if (total == 0) {
return new PageResult.Builder<T>()
.pageNo(pageNo)
.pageSize(pageSize)
.total(total)
.result(Collections.emptyList())
.build();
}
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);
}
return new PageResult.Builder<T>()
.pageNo(pageNo)
.pageSize(pageSize)
.total(total)
.result(records)
.build();
}
public static int calculateOffset(int pageNo, int pageSize) {
return (pageNo - 1) * pageSize;
}
}
4.使用方式
1.DTO实体类继承PageInfo
2.具体使用
1.传入pageNo和pageSize
2.传入计算数量的逻辑
3.传入分页查询的逻辑
@Override
public PageResult<SysUser> queryByPage(SysUser sysUser) {
return SunPageHelper.paginate(sysUser.getPageNo(), sysUser.getPageSize(),
() -> sysUserMapper.count(sysUser),
(offset, size) -> sysUserMapper.queryPage(sysUser, offset, size)
);
}