解決jpa用原生sql無法分頁的問題
阿新 • • 發佈:2018-11-11
1、獲取介面傳來的分頁引數
String page_id=request.getParameter("page_id");//頁碼 String limit=request.getParameter("limit"); //每頁資料條數 //判斷為空時賦予初始值 if(StringUtils.isBlank(page_id)){ page_id="1"; } if(StringUtils.isBlank(limit)){ limit="10"; } //用PageRequest 接收分頁引數 PageRequest pageRequest = PageRequest.of(Integer.parseInt(page_id) - 1, Integer.parseInt(limit));
2、業務層呼叫jpa查詢
List<Map<String, Object>> comments = postCommentRepository.findCommentList("0", post_id, customerEntity.getId(), Integer.parseInt(pageRequest.getOffset()+""),pageRequest.getPageSize());
3、jpa用原聲sql查詢(nativeQuery = true)
加limit 使用傳來的pageOffset和pageSize限制查詢幾條即可
此時要用List接收查詢的資料,而不能用Page接收
@Query(value = "(select id id,content content,audit_flag audit_flag,create_date create_time," + "customer_id customer_id " + "from post_comment " + "where del_flag=?1 and post_id=?2 and audit_flag='1')" + "union " + "(select id id,content content,audit_flag audit_flag,create_date create_time," + "customer_id customer_id " + "from post_comment " + "where del_flag=?1 and post_id=?2 and customer_id=?3 and audit_flag in('0','2'))" + "limit ?4,?5",nativeQuery = true) List<Map<String,Object>> findCommentList(String delFlag,String post_id,String customerId,int pageOffset,int pageSize);
注意:我這裡用的是union聯合查詢,要對查出的整體資料進行分頁,則需要將union兩邊的sql用括號包起來