使用github的pagehelper分頁依賴
<!-- 分頁控件 --><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.3.0</version><scope>compile</scope></dependency><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.4.1</version><exclusions><exclusion><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId></exclusion><exclusion><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId></exclusion></exclusions></dependency>
分頁方式一:使用pageheler直接對查詢語句生效(如果查詢后還需對數據進行二次處理,此分頁方式失效)
public PageInfo<AlarmReportInfo> getReportInfoList(ReportInfoVO info) {//分頁操作if (info.getPage() != null && info.getRows() != null) {PageHelper.startPage(info.getPage(), info.getRows());}//查詢出系統原有所有的List<AlarmReportInfo> reportInfoAllList = b_alarmReportInfoMapper.getReportInfoList(info);PageInfo<AlarmReportInfo> data = new PageInfo<>(reportInfoAllList );data.setTotal(reportInfoAllList .size());return data;
此時分頁只針對b_alarmReportInfoMapper.getReportInfoList(info)函數生效,得到的結果就是分頁之后的結果。
分頁方式二:先合并數據,再進行分頁(此方式適用于對數據進行二次處理的應用)
public PageInfo<AlarmReportInfo> getReportInfoList(ReportInfoVO info) {// 查詢系統原有所有的報告List<AlarmReportInfo> reportInfoAllList = b_alarmReportInfoMapper.getReportInfoList(info);// 手動分頁int total = reportInfoAllList .size(); // 記錄總數int fromIndex = (info.getPage() - 1) * info.getRows();int toIndex = Math.min(fromIndex + info.getRows(), total);// 防止下標越界if (fromIndex > total) {fromIndex = total;toIndex = total;}List<AlarmReportInfo> pageData = reportInfoAllList .subList(fromIndex, toIndex);// 使用 PageInfo 包裝分頁后的數據PageInfo<AlarmReportInfo> data = new PageInfo<>(pageData);data.setTotal(total); // 設置總記錄數return data;
}
或者使用
public PageInfo<AlarmReportInfo> getReportInfoList(ReportInfoVO info) {// 查詢系統原有所有的報告List<AlarmReportInfo> reportInfoAllList = b_alarmReportInfoMapper.getReportInfoList(info);// 手動分頁int total = reportInfoAllList.size(); // 記錄總數int size = reportInfoAllList.size();if (info.getPage() != null && info.getRows() != null) {reportInfoAllList= reportInfoAllList.subList((info.getPage() - 1) * info.getRows(), ((info.getPage() - 1) * info.getRows()) + info.getRows() > reportInfoAllList.size() ? reportInfoAllList.size() : ((info.getPage() - 1) * info.getRows()) + info.getRows());}// 使用 PageInfo 包裝分頁后的數據PageInfo<AlarmReportInfo> data = new PageInfo<>(reportInfoAllList);data.setTotal(total); // 設置總記錄數return data;
}