PageHelper.startPage(int pageNum, int pageSize, boolean count)
參數(shù)為外部輸入,故存在異常輸入場景。比如 pageNum
和 pageSize
輸入的值 負數(shù)
或者 0
,所以引入PageUtils
來對入?yún)⑦M行判斷矯正,從而避免引入異常。
第1步:支持配置的方式來修改默認值
page-helper:
default-page-num: 1
default-page-size: 10
max-page-size: 50
count-total-or-not: true
第2步:引入PageUtils
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Objects;
@Component
public class PageUtils {
private static int defaultPageNumber; // 默認顯示第幾頁
private static int defaultPageSize; // 默認每頁顯示多少條數(shù)據(jù)
private static int maxSizePage; // 每頁顯示條數(shù)上限
private static boolean isQueryTotalCount; // 每次查詢DB時,是否進行count查詢
@Value("${page-helper.default-page-num:1}")
private int pageNumberFromConfig;
@Value("${page-helper.default-page-size:10}")
private int pageSizeFromConfig;
@Value("${page-helper.max-page-size:15}")
private int maxSizePerPageFromConfig;
@Value("${page-helper.count-total-or-not:true}")
private boolean isQueryTotalFromConfig;
@PostConstruct
private void init() {
defaultPageNumber = pageNumberFromConfig;
defaultPageSize = pageSizeFromConfig;
maxSizePage = maxSizePerPageFromConfig;
isQueryTotalCount = isQueryTotalFromConfig;
}
public static int getPageNum(Integer pageNum) {
if (Objects.isNull(pageNum) || pageNum <= 0) {
return defaultPageNumber;
} else {
return pageNum;
}
}
public static int getPageSize(Integer pageSize) {
if (Objects.isNull(pageSize) || pageSize <= 0) {
return defaultPageSize;
} else if (pageSize > 100) {
return maxSizePage;
} else {
return pageSize;
}
}
public static boolean isQueryTotalCount() {
return isQueryTotalCount;
}
}
第3步:使用
public List<Student> listStudents(Integer pageNum, Integer PageSize) {
PageHelper.startPage(PageUtils.getPageNum(pageNum), PageUtils.getPageSize(PageSize), PageUtils.isQueryTotalCount());
PageHelper.orderBy("age asc");
List<Student> students = userMapper.listStudents();
PageInfo<Student> studentPageInfo = PageInfo.of(students);
return students;
}
文章來源:http://www.zghlxwxcb.cn/news/detail-810452.html
參考
@PostConstruct 的執(zhí)行時機文章來源地址http://www.zghlxwxcb.cn/news/detail-810452.html
到了這里,關于SpringBoot 如何增強PageHelper入?yún)⒌慕研缘奈恼戮徒榻B完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!