From 7eea5ed7e09a7c1a45963bf19b4a9afbef2de85e Mon Sep 17 00:00:00 2001 From: ZhouXY108 Date: Tue, 8 Nov 2022 13:52:44 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=86=20PageDTO=20=E5=92=8C=20PagingAndSort?= =?UTF-8?q?ingQueryParams=20=E6=B7=BB=E5=8A=A0=E5=88=B0=20plusone-commons?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/xyz/zhouxy/plusone/util/PageDTO.java | 40 ++++++++++++++ .../util/PagingAndSortingQueryParams.java | 53 +++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 src/main/java/xyz/zhouxy/plusone/util/PageDTO.java create mode 100644 src/main/java/xyz/zhouxy/plusone/util/PagingAndSortingQueryParams.java diff --git a/src/main/java/xyz/zhouxy/plusone/util/PageDTO.java b/src/main/java/xyz/zhouxy/plusone/util/PageDTO.java new file mode 100644 index 0000000..dce9bc8 --- /dev/null +++ b/src/main/java/xyz/zhouxy/plusone/util/PageDTO.java @@ -0,0 +1,40 @@ +package xyz.zhouxy.plusone.util; + +import java.util.List; + +import lombok.Setter; +import lombok.ToString; + +/** + * 返回分页查询的结果 + * + * @param 内容列表的元素类型 + * + * @author ZhouXY + * @see PagingAndSortingQueryParams + */ +@ToString +@Setter +public class PageDTO { + + private Long total; + private List content; + + private PageDTO(List content, Long total) { + this.content = content; + this.total = total; + } + + public static PageDTO of(List content, Long total) { + return new PageDTO<>(content, total); + } + + public Long getTotal() { + return total; + } + + public List getContent() { + return content; + } + +} diff --git a/src/main/java/xyz/zhouxy/plusone/util/PagingAndSortingQueryParams.java b/src/main/java/xyz/zhouxy/plusone/util/PagingAndSortingQueryParams.java new file mode 100644 index 0000000..78b2ddf --- /dev/null +++ b/src/main/java/xyz/zhouxy/plusone/util/PagingAndSortingQueryParams.java @@ -0,0 +1,53 @@ +package xyz.zhouxy.plusone.util; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import lombok.Setter; + +/** + * 分页排序查询参数 + * + *

+ * 根据传入的 {@code size} 和 {@code pageNum}, + * 提供 {@code getOffset} 方法计算 SQL 语句中 {@code offset} 的值。 + *

+ * + * @author ZhouXY + * @see PageDTO + */ +@Setter +public class PagingAndSortingQueryParams { + + protected String orderBy; + protected Integer size; + protected Long pageNum; + + private final List sortableColNames; + + public PagingAndSortingQueryParams() { + sortableColNames = Collections.emptyList(); + } + + public PagingAndSortingQueryParams(String... sortableColNames) { + this.sortableColNames = Arrays.asList(sortableColNames); + } + + public String getOrderBy() { + return orderBy != null && sortableColNames.contains(orderBy) ? orderBy : null; + } + + public int getSize() { + return this.size != null ? this.size : 15; + } + + public long getPageNum() { + return this.pageNum != null ? this.pageNum : 1; + } + + public long getOffset() { + return (getPageNum() - 1) * getSize(); + } + +}