注解@Query進行自動分頁查詢


直接傳自帶的實體類Pageable,並設置參數即可,JPA會自動識別並解析分頁SQL,如此來看,JPA還是考慮得挺周全的

參數直接傳Pageable

@Query("SELECT DISTINCT c FROM Customer c JOIN c.partyCerts p where p.certNum=?")
	public List<Customer> findCustomerListByNum(String certNum,Pageable pageable);

分頁並自定義反參

@Query("select new ResultInfo(r.displayName,r.result.id,r.result.createdDate,r.result.createdBy.displayName) from ResultInfo r where r.result.id not in ?1 and r.secUser.id<>?2 and r.createdBy.id<>?3 and r.creator=?4")
    Page<ResultInfo> findToBeSharedResultInfoeListTwo(List<String>beSharedIdList,
                                                      String secUserId,
                                                      String createdById,
                                                      Boolean creator,
                                                      Pageable pageable);
public ResultInfo(String displayName,String resultId,Date resultCreateDate,String resultCreatedByDisplayName) {
		this.setDisplayName(displayName);
		Result result = new Result();
		result.setCreatedDate(resultCreateDate);
		SecUser secUser = new SecUser();
		secUser.setDisplayName(resultCreatedByDisplayName);
		result.setCreatedBy(secUser);
		result.setId(resultId);
		this.result=result;
	}

在這里插入圖片描述
當反參類型為Page類型時,@Query中有個屬性是countQuery,此屬性的作用是定義查詢總數的sql,如果不使用此屬性,總數sql由框架自己生成

Paging query needs to have a Pageable parameter!

如下:當接口參數類型用Page時,入參必須有Pageable類型參數

@Query("select new ResultInfo(r.displayName,r.result.id,r.result.createdDate,r.result.createdBy.displayName) from ResultInfo r where r.secUser.id<>?1 and r.createdBy.id<>?2 and r.creator=?3")
    Page<ResultInfo> findToBeSharedResultInfoeList(String secUserId,
                                                   String createdById,
                                                   Boolean creator);

Cannot use native queries with dynamic sorting and/or pagination in method

如下:當使用原生本地sql時,不能通過傳Pageable參數實現分頁,必須通過sql方式方式分頁,例如mysql使用limit

@Query(value = "select r.* from VBAP3_RESULT_INFO r " +
            "left join VBAP3_SEC_USER secUser on r.sec_user_id=secUser.id " +
            "left join VBAP3_SEC_USER creatUser on r.created_by_id=creatUser.id " +
            "where secUser.id<>?1 and creatUser.id<>?2 and r.creator=?3",nativeQuery = true)
    List<ResultInfo> testOne(String secUserId,String createdById,Boolean creator,Pageable pageable);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM