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(); + } + +}