diff --git a/src/main/java/icu/sunway/ai_spring_example/Utils/PageUtils.java b/src/main/java/icu/sunway/ai_spring_example/Utils/PageUtils.java new file mode 100644 index 0000000..b2acda4 --- /dev/null +++ b/src/main/java/icu/sunway/ai_spring_example/Utils/PageUtils.java @@ -0,0 +1,111 @@ +package icu.sunway.ai_spring_example.Utils; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +/** + * 分页工具类 + */ +public class PageUtils { + + /** + * 默认页码 + */ + public static final Integer DEFAULT_PAGE = 1; + + /** + * 默认每页数量 + */ + public static final Integer DEFAULT_LIMIT = 10; + + /** + * 最大每页数量 + */ + public static final Integer MAX_LIMIT = 100; + + /** + * 分页结果类 + * + * @param 数据类型 + */ + @Data + @AllArgsConstructor + @NoArgsConstructor + public static class PaginationResult { + private Integer currentPage; + private Integer pageSize; + private Long totalItems; + private Integer totalPages; + private List list; + } + + /** + * 验证和调整分页参数 + * + * @param page 页码 + * @param limit 每页数量 + * @return 调整后的分页参数数组 [page, limit] + */ + public static Integer[] validatePageParams(Integer page, Integer limit) { + // 验证页码 + if (page == null || page < 1) { + page = DEFAULT_PAGE; + } + + // 验证每页数量 + if (limit == null || limit < 1 || limit > MAX_LIMIT) { + limit = DEFAULT_LIMIT; + } + + return new Integer[] { page, limit }; + } + + /** + * 创建Page对象 + * + * @param page 页码 + * @param limit 每页数量 + * @return Page对象 + */ + public static Page createPage(Integer page, Integer limit) { + Integer[] params = validatePageParams(page, limit); + return new Page<>(params[0], params[1]); + } + + /** + * 将MyBatis Plus的Page结果转换为分页结果 + * + * @param pageResult MyBatis Plus的Page结果 + * @return 分页结果 + */ + public static PaginationResult createPaginationResult(IPage pageResult) { + return new PaginationResult<>( + (int) pageResult.getCurrent(), + (int) pageResult.getSize(), + pageResult.getTotal(), + (int) pageResult.getPages(), + pageResult.getRecords()); + } + + /** + * 创建空的分页结果 + * + * @param page 页码 + * @param limit 每页数量 + * @return 空的分页结果 + */ + public static PaginationResult createEmptyPaginationResult(Integer page, Integer limit) { + Integer[] params = validatePageParams(page, limit); + return new PaginationResult<>( + params[0], + params[1], + 0L, + 0, + List.of()); + } +}