文章目錄
- 1. 引入依賴
- 1.1 Gangbb-Vue的pom.xml
- 1.2 Gangbb-common的pom.xml
- 2.配置yml
- 3. 封裝分頁相關工具
- 3.1 BaseController
- 3.2 TableDataInfo
- 3.3 資料傳輸類PageDto
- 3.4 一些工具類
專案地址:https://github.com/Gang-bb/Study-Record/tree/main/Gangbb-Vue
本章結束后對應的節選代碼檔案:Gangbb-Vue-09-PageHelper歷史遺留TODO:
- 第四章
- 登錄日志還未實作,(到登錄和權限模塊完成)
LogAspect從快取獲取當前的用戶資訊使用模擬的資料(到登錄和權限模塊完成)本章將留下TODO:
- 無
本章將解決TODO:
- 無
本來這章應該跟Mybatis一起的,給落下了,現在補回來
1. 引入依賴
1.1 Gangbb-Vue的pom.xml
在第三章中已經在Gangbb-Vue引入了分頁的依賴,
1.2 Gangbb-common的pom.xml
<dependencies>
<!-- pagehelper 分頁插件 begin-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency>
<!-- pagehelper 分頁插件 end-->
</dependencies>
2.配置yml
# PageHelper分頁插件
pagehelper:
# 指定分頁插件使用哪種資料庫方言
helperDialect: mysql
# 當該引數設定為 true 時,pageNum<=0 時會查詢第一頁, pageNum>pages(超過總數時),會查詢最后一頁,
reasonable: true
# 支持通過 Mapper 介面引數來傳遞分頁引數,默認值false,分頁插件會從查詢方法的引數值中,自動根據上面 params 配置的欄位中取值,查找到合適的值時就會自動分頁,
supportMethodsArguments: true
這里簡單配置了幾項,
所有配置項:
helperDialect:分頁插件會自動檢測當前的資料庫鏈接,自動選擇合適的分頁方式, 你可以配置helperDialect屬性來指定分頁插件使用哪種方言,配置時,可以使用下面的縮寫值:
oracle,mysql,mariadb,sqlite,hsqldb,postgresql,db2,sqlserver,informix,h2,sqlserver2012,derby
**特別注意:**使用 SqlServer2012 資料庫時,需要手動指定為sqlserver2012,否則會使用 SqlServer2005 的方式進行分頁,
你也可以實作AbstractHelperDialect,然后配置該屬性為實作類的全限定名稱即可使用自定義的實作方法,offsetAsPageNum:默認值為false,該引數對使用RowBounds作為分頁引數時有效, 當該引數設定為true時,會將RowBounds中的offset引數當成pageNum使用,可以用頁碼和頁面大小兩個引數進行分頁,rowBoundsWithCount:默認值為false,該引數對使用RowBounds作為分頁引數時有效, 當該引數設定為true時,使用RowBounds分頁會進行 count 查詢,pageSizeZero:默認值為false,當該引數設定為true時,如果pageSize=0或者RowBounds.limit = 0就會查詢出全部的結果(相當于沒有執行分頁查詢,但是回傳結果仍然是Page型別),reasonable:分頁合理化引數,默認值為false,當該引數設定為true時,pageNum<=0時會查詢第一頁,pageNum>pages(超過總數時),會查詢最后一頁,默認false時,直接根據引數進行查詢,params:為了支持startPage(Object params)方法,增加了該引數來配置引數映射,用于從物件中根據屬性名取值, 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默認值, 默認值為pageNum=pageNum;pageSize=pageSize;count=countSql;reasonable=reasonable;pageSizeZero=pageSizeZero,supportMethodsArguments:支持通過 Mapper 介面引數來傳遞分頁引數,默認值false,分頁插件會從查詢方法的引數值中,自動根據上面params配置的欄位中取值,查找到合適的值時就會自動分頁, 使用方法可以參考測驗代碼中的com.github.pagehelper.test.basic包下的ArgumentsMapTest和ArgumentsObjTest,autoRuntimeDialect:默認值為false,設定為true時,允許在運行時根據多資料源自動識別對應方言的分頁 (不支持自動選擇sqlserver2012,只能使用sqlserver),用法和注意事項參考下面的場景五,closeConn:默認值為true,當使用運行時動態資料源或沒有設定helperDialect屬性自動獲取資料庫型別時,會自動獲取一個資料庫連接, 通過該屬性來設定是否關倍訓取的這個連接,默認true關閉,設定為false后,不會關倍訓取的連接,這個引數的設定要根據自己選擇的資料源來決定,aggregateFunctions(5.1.5+):默認為所有常見資料庫的聚合函式,允許手動添加聚合函式(影響行數),所有以聚合函式開頭的函式,在進行 count 轉換時,會套一層,其他函式和列會被替換為 count(0),其中count列可以自己配置,
更多資訊可以可以看官方檔案:
? https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md
3. 封裝分頁相關工具
3.1 BaseController
這是一個web層通用處理類,核心方法startPage()請求分頁資料方法,使繼承BaseController的Controller可以快速使用分頁,
public class BaseController {
protected final Logger logger = LoggerFactory.getLogger(BaseController.class);
/**
* 將前臺傳遞過來的日期格式的字串,自動轉化為Date型別
*/
@InitBinder
public void initBinder(WebDataBinder binder)
{
// Date 型別轉換
binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
{
@Override
public void setAsText(String text)
{
setValue(DateUtils.parseDate(text));
}
});
}
/**
* 設定請求分頁資料
*/
protected void startPage()
{
//從前端獲取分頁引數
MyPage pageDomain = TableSupport.buildPageRequest();
Integer pageNum = pageDomain.getPageNum();
Integer pageSize = pageDomain.getPageSize();
if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
{
String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
PageHelper.startPage(pageNum, pageSize, orderBy);
}
}
/**
* 回應請求分頁資料
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected TableDataInfo getDataTable(List<?> list)
{
TableDataInfo rspData = new TableDataInfo();
rspData.setCode(HttpStatus.SUCCESS);
rspData.setMsg("查詢成功");
rspData.setRows(list);
rspData.setTotal(new PageInfo(list).getTotal());
return rspData;
}
/**
* 回應回傳結果
*
* @param rows 影響行數
* @return 操作結果
*/
protected ApiRestResponse toApiRes(int rows)
{
return rows > 0 ? ApiRestResponse.success() : ApiRestResponse.error();
}
/**
* 頁面跳轉
*/
public String redirect(String url)
{
return StringUtils.format("redirect:{}", url);
}
}
3.2 TableDataInfo
若依封裝的自定義分頁結果,只有4個引數,感覺不太夠,還是Pagehelper提供的PageInfo類回傳的資訊比較全,
對比一下便知:
若依TableDataInfo回傳的資訊:
{
"total": 5,
"rows": [
{
"creator": "",
"createTime": "2021-03-10 15:04:32",
"reviser": "",
"updateTime": null,
"isDel": 0,
"remark": "",
"id": 1160,
"title": "測驗系統自定義例外",
"businessType": 0,
"businessTypes": null,
"classMethod": "com.gangbb.test.controller.TestExceptionController.testApiException()",
"requestMethod": "GET",
"operatorType": 1,
"operationName": "Gangbb",
"operationUrl": "/test/exception/e",
"operationIp": "127.0.0.1",
"operationLocation": "內網IP",
"operationParam": "{}",
"jsonResult": "null",
"operationStatus": 1,
"errorMsg": "System internal errors",
"operationTime": "2021-03-10 15:04:32"
},
{
"creator": "",
"createTime": "2021-03-10 15:05:43",
"reviser": "",
"updateTime": null,
"isDel": 0,
"remark": "",
"id": 1161,
"title": "測驗success",
"businessType": 0,
"businessTypes": null,
"classMethod": "com.gangbb.test.controller.TestExceptionController.testSuccess()",
"requestMethod": "POST",
"operatorType": 1,
"operationName": "Gangbb",
"operationUrl": "/test/exception/success",
"operationIp": "127.0.0.1",
"operationLocation": "內網IP",
"operationParam": "",
"jsonResult": "{\"code\":\"20000\",\"msg\":\"操作成功(success)\",\"data\":{\"info\":\"Test\",\"name\":\"LLL\"}}",
"operationStatus": 0,
"errorMsg": null,
"operationTime": "2021-03-10 15:05:43"
}
],
"code": 200,
"msg": "查詢成功"
}
TableDataInfo類代碼自行看專案檔案,不再貼出,
PageInfo回傳的資訊:
{
"total": 5,
"list": [
{
"creator": "",
"createTime": "2021-03-10 15:04:32",
"reviser": "",
"updateTime": null,
"isDel": 0,
"remark": "",
"id": 1160,
"title": "測驗系統自定義例外",
"businessType": 0,
"businessTypes": null,
"classMethod": "com.gangbb.test.controller.TestExceptionController.testApiException()",
"requestMethod": "GET",
"operatorType": 1,
"operationName": "Gangbb",
"operationUrl": "/test/exception/e",
"operationIp": "127.0.0.1",
"operationLocation": "內網IP",
"operationParam": "{}",
"jsonResult": "null",
"operationStatus": 1,
"errorMsg": "System internal errors",
"operationTime": "2021-03-10 15:04:32"
},
{
"creator": "",
"createTime": "2021-03-10 15:05:43",
"reviser": "",
"updateTime": null,
"isDel": 0,
"remark": "",
"id": 1161,
"title": "測驗success",
"businessType": 0,
"businessTypes": null,
"classMethod": "com.gangbb.test.controller.TestExceptionController.testSuccess()",
"requestMethod": "POST",
"operatorType": 1,
"operationName": "Gangbb",
"operationUrl": "/test/exception/success",
"operationIp": "127.0.0.1",
"operationLocation": "內網IP",
"operationParam": "",
"jsonResult": "{\"code\":\"20000\",\"msg\":\"操作成功(success)\",\"data\":{\"info\":\"Test\",\"name\":\"LLL\"}}",
"operationStatus": 0,
"errorMsg": null,
"operationTime": "2021-03-10 15:05:43"
}
],
"pageNum": 1,
"pageSize": 2,
"size": 2,
"startRow": 1,
"endRow": 2,
"pages": 3,
"prePage": 0,
"nextPage": 2,
"isFirstPage": true,
"isLastPage": false,
"hasPreviousPage": false,
"hasNextPage": true,
"navigatePages": 8,
"navigatepageNums": [
1,
2,
3
],
"navigateFirstPage": 1,
"navigateLastPage": 3
}
3.3 資料傳輸類PageDto
若依原始碼中叫PageDomain類
主要的屬性:
/** 當前記錄起始索引 */
private Integer pageNum;
/** 每頁顯示記錄數 */
private Integer pageSize;
/** 排序列 */
private String orderByColumn;
/** 排序的方向desc或者asc */
private String isAsc = "asc";
這是前端呼叫介面時,可選擇傳入的引數,
而引數傳遞的宣告,沒有寫在各個使用分頁方法的引數串列中,直接通過TableSupport從客戶端工具類ServletUtils中獲取分頁請求的各項可填引數,
但是若依如此設計,實測沒有進行引數校驗,例如:
pageNum傳入一個字母,這時回傳的結果是全部資料也未分頁,對于前端是不利于排查的,
使用時可以增加一些適當的校驗,例如:
(只是舉例,實際應用應該更嚴謹一點)
校驗:
本章在全域錯誤處理GlobalExceptionHandler增加了對MethodArgumentTypeMismatchException引數轉換例外的處理,
/**
* MethodArgumentTypeMismatchException 引數型別轉換例外
*/
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ApiRestResponse resolveMethodArgumentNotValidException(MethodArgumentTypeMismatchException ex){
String msg = "引數<" + ex.getName() + ">校驗失敗:" + ex.getMessage();
return ApiRestResponse.error("A0003", msg);
}
3.4 一些工具類
DateUtils:時間工具類
TableSupport:獲取分頁引數
SqlUtil:sql操作工具類
(代碼自行到專案中復制)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/279875.html
標籤:其他
