由於springboot jpa 原生的 findAll 是從第0頁開始的,因此如果想使用自帶的分頁配合jqgrid使用需要進行處理。
1、在查詢時,先進行-1操作
@GetMapping("/goods/list")
public @ResponseBody Page<SkuInfo> queryGoodsInfos(String venderSku, Pageable pageable)
{
if(!StringUtils.isEmpty(venderSku))
{
return skuRepository.findAllByVenderSku(venderSku,pageable);
}
else
{
Pageable reallyPageable=new PageRequest(pageable.getPageNumber()==0?0:pageable.getPageNumber()-1,pageable.getPageSize(),pageable.getSort());
return skuRepository.findAll(reallyPageable);
}
}
2、在返回內容到前台顯示時,進行當前頁面+1操作
jsonReader: {
root: "content", // json中代表實際deliverInfo 這個
page: "number+1", // json中代表當前頁碼的數據
total: "totalPages", // json中代表頁碼總數的數據
records: "totalElements" // json中代表數據行總數的數據
// subgrid: {root: "data"}
}
下面附上實例,實例A為最簡單的直接使用findAll
controller如下:
/** * 商品信息管理界面 */ @Controller public class GoodsInfoController { @Autowired private SkuRepository skuRepository; @GetMapping("/goods/man") public String getGoodsInfoIndex() { return "admin/goods"; } // @GetMapping("/goods/{venderSku}") // public @ResponseBody List<SkuInfo> getGoodsInfo(@PathVariable String venderSku) // { // return skuRepository.findSkuInfosByVenderSku(venderSku); // } @GetMapping("/goods/list") public @ResponseBody Page<SkuInfo> queryGoodsInfos(String venderSku, Pageable pageable) { if(!StringUtils.isEmpty(venderSku)) { return skuRepository.findAllByVenderSku(venderSku,pageable); } else { Pageable reallyPageable=new PageRequest(pageable.getPageNumber()==0?0:pageable.getPageNumber()-1,pageable.getPageSize(),pageable.getSort()); return skuRepository.findAll(reallyPageable); } } }
jqgrid相關的js如下:
function pageInit() { jQuery("#grid").jqGrid({ url: '/goods/list', datatype: "json", ajaxGridOptions: {contentType: 'application/json; charset=utf-8'}, // postData:{beginDate:'2017-02-02',endDate:'2018-03-03',orderId:333}, colNames: ['商家SKU', '可銷庫存', '批發價', '有效期至', '單體價', '加盟價', '連鎖價', '醫療價', '商業價', '最后修改時間'], colModel: [ {name: 'venderSku', index: 'venderSku', width: 80}, {name: 'skuStock', index: 'skuStock', width: 20}, { name: 'skuPrice', index: 'skuPrice', align: "left", sortable: false, width: 80, formatter: 'number', formatoptions: {thousandsSeparator: ",", defaulValue: "", decimalPlaces: 2} }, {name: 'validTime', index: 'validTime', width: 30}, { name: 'monomersPrice', index: 'monomersPrice', align: "left", sortable: false, width: 30, formatter: 'number', formatoptions: {thousandsSeparator: ",", defaulValue: "", decimalPlaces: 2} }, { name: 'joinInPrice', index: 'joinInPrice', align: "left", sortable: false, width: 30, formatter: 'number', formatoptions: {thousandsSeparator: ",", defaulValue: "", decimalPlaces: 2} }, { name: 'chainPrice', index: 'chainPrice', align: "left", sortable: false, width: 30, formatter: 'number', formatoptions: {thousandsSeparator: ",", defaulValue: "", decimalPlaces: 2} }, { name: 'medicalCarePrice', index: 'medicalCarePrice', align: "left", sortable: false, width: 30, formatter: 'number', formatoptions: {thousandsSeparator: ",", defaulValue: "", decimalPlaces: 2} }, { name: 'businessPrice', index: 'businessPrice', align: "left", sortable: false, width: 30, formatter: 'number', formatoptions: {thousandsSeparator: ",", defaulValue: "", decimalPlaces: 2} }, { name: 'lastModifyTime', index: 'lastModifyTime', width: 100, formatter: "date", formatoptions: {srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s'} } ], rowNum: 10, rowList: [10, 20, 30], pager: '#pager2', sortname: 'venderSku', mtype: "GET", postData: $("#searchForm").serializeJSON(), viewrecords: true, sortorder: "desc", emptyrecords: "暫無數據", autowidth: true, rownumbers:true, caption: "用戶ERP中提取到的商品信息", loadonce: false, //如果為ture則數據只從服務器端抓取一次,之后所有操作都是在客戶端執行,翻頁功能會被禁用 loadComplete: function () { }, prmNames: { page: "page", // 表示請求頁碼的參數名稱 rows: "size", // 表示請求行數的參數名稱 totalrows: "totalElements"//表示一共有多少條數據 //sort: "sortFieldName", // 表示用於排序的列名的參數名稱 //order: "sort" // 表示采用的排序方式的參數名稱 }, jsonReader: { root: "content", // json中代表實際模型數據的入口 page: "number+1", // json中代表當前頁碼的數據 total: "totalPages", // json中代表頁碼總數的數據 records: "totalElements" // json中代表數據行總數的數據 // subgrid: {root: "data"} } }); }
實例B,需要傳入beginDate,endDate這種同一個參數多個值的,即簡單查詢搞不定的。需要引入JpaSpecificationExecutor
repositroy如下:
public interface DeliverRepository extends JpaRepository<DeliverInfo,Long>, JpaSpecificationExecutor<DeliverInfo> { /** * 獲取指定回寫狀態訂單 * @param rewriteState * @return */ List<DeliverInfo> findByrewriteState(int rewriteState); /** * 更新回寫狀態 * @param rewriteState * @param orderId * @return */ @Transactional @Modifying @Query(value = "update DeliverInfo set rewriteState=:rewriteState where orderId=:orderId") int updateReWriteState(@Param("rewriteState") Integer rewriteState, @Param("orderId") Long orderId); /** * 更新重試次數 * @param retryTimes * @param orderId * @return */ @Transactional @Modifying @Query(value = "update DeliverInfo set retry_times=:retryTimes where orderId=:orderId") int updateretryTimes(@Param("retryTimes") Integer retryTimes, @Param("orderId") Long orderId);
congroller如下:
@Controller public class DeliverInfoManController { @Autowired private DeliverRepository deliverRepository; @GetMapping("/deliver/man") public String getDeliverInfoIndex() { return "admin/deliver"; } @GetMapping("/deliver/list") public @ResponseBody Page<DeliverInfo> getDeliverInfoList(DeliverInfoQuery query,Pageable pageable) { return this.getDataList(query, pageable); } private Page<DeliverInfo> getDataList(DeliverInfoQuery deliverInfoQuery,Pageable pageable) { Specification<DeliverInfo> querySpecifi = new Specification<DeliverInfo>() { public Predicate toPredicate(Root<DeliverInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { List<Predicate> predicates = new ArrayList<>(); if (!StringUtils.isEmpty(deliverInfoQuery.getBeginDate())) { //大於或等於傳入時間 predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("orderTime").as(String.class), deliverInfoQuery.getBeginDate())); } if (!StringUtils.isEmpty(deliverInfoQuery.getEndDate())) { //小於或等於傳入時間 predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("orderTime").as(String.class), deliverInfoQuery.getEndDate())); } if (deliverInfoQuery != null) { Class<? extends DeliverInfoQuery> clazz = deliverInfoQuery.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field tmpField : fields) { tmpField.setAccessible(true); try { if (tmpField.get(deliverInfoQuery) != null && !tmpField.getName().equals("beginDate") && !tmpField.getName().equals("endDate")) //不為空的查詢參數才拼查詢條件,並且要去掉額外加上的時間范圍條件 { String name = tmpField.getName(); predicates.add(criteriaBuilder.equal(root.get(name), tmpField.get(deliverInfoQuery))); // if (tmpField.getType().equals(String.class) && !StringUtils.isEmpty((String)tmpField.get(orderQuery))) //只拼字符串查詢條件的,因為目前只需要按照 訂單號、退款狀態來查詢 // { // String name = tmpField.getName(); // predicates.add(criteriaBuilder.equal(root.get(name), tmpField.get(orderQuery))); // } } } catch (IllegalAccessException e) { e.printStackTrace(); } } } // and到一起的話所有條件就是且關系,or就是或關系 return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); } }; Sort sort = new Sort(Sort.Direction.DESC, "orderTime"); Pageable reallyPageable=new PageRequest(pageable.getPageNumber()==0?0:pageable.getPageNumber()-1,pageable.getPageSize(),pageable.getSort()); return deliverRepository.findAll(querySpecifi,reallyPageable); } }
jqgrid 相關js如下:
function pageInit() { jQuery("#grid").jqGrid({ url: '/deliver/list', datatype: "json", ajaxGridOptions: {contentType: 'application/json; charset=utf-8'}, // postData:{beginDate:'2017-02-02',endDate:'2018-03-03',orderId:333}, colNames: ['訂單號', '配送方式', '商家編碼', '快遞單號', '物流公司編號', '物流公司名稱', '回寫標示', '重試次數'], colModel: [ {name: 'orderId', index: 'orderId', width: 40}, {name: 'shipmentType', index: 'shipmentType', width: 40}, {name: 'customerCode', index: 'customerCode', width: 40}, {name: 'deliveryId', index: 'deliveryId', width: 30}, {name: 'logiNo', index: 'logiNo', width: 20}, {name: 'logiCompany', index: 'logiCompany', width: 40}, {name: 'rewriteState', index: 'rewriteState', width: 20}, {name: 'retryTimes', index: 'retryTimes', width: 20} ], rowNum: 10, rowList: [10, 20, 30,5], pager: '#pager2', sortname: 'orderId', mtype: "GET", postData: $("#searchForm").serializeJSON(), viewrecords: true, sortorder: "desc", emptyrecords: "暫無數據", autowidth: true, rownumbers:true, caption: "從ERP種獲取到的待回寫物流信息", loadonce: false, //如果為ture則數據只從服務器端抓取一次,之后所有操作都是在客戶端執行,翻頁功能會被禁用 loadComplete: function () { }, prmNames: { page: "page", // 表示請求頁碼的參數名稱 rows: "size", // 表示請求行數的參數名稱 totalrows: "totalElements"//表示一共有多少條數據 //sort: "sortFieldName", // 表示用於排序的列名的參數名稱 //order: "sort" // 表示采用的排序方式的參數名稱 }, jsonReader: { root: "content", // json中代表實際deliverInfo 這個 page: "number+1", // json中代表當前頁碼的數據 total: "totalPages", // json中代表頁碼總數的數據 records: "totalElements" // json中代表數據行總數的數據 // subgrid: {root: "data"} } }); }
