简体   繁体   中英

Implement pagination using Java (Named Query)

Here is the scenario. I had a page with a list of records shown all (without pagination).

Now at the backend side, the records are retrieved with a combination of 2 separate named queries for each part (one each for actual records/count of part1/part2);

@NamedQuery(name = "CustomDOTO.findPart1", query = "SELECT part1";
@NamedQuery(name = "CustomDOTO.findPart1Count", query = "SELECT count(part1)";
@NamedQuery(name = "CustomDOTO.findPart2", query = "SELECT part2";
@NamedQuery(name = "CustomDOTO.findPart2Count", query = "SELECT count(part2)";

Now I need to implement pagination for the same. So I use a custom class PagedResponse for the same which actually just consists 2 things;

private Long totalRecords;
private List<T> records;

Also I use a custom method runPaginatedQuery to return paginated response;

protected <T> PagedResponse<T> runPaginatedQuery(Query query, Query cntQuery, int startingResult, int maxResults) {

}

My question is since I have 2 separate named queries, if I call the runPaginatedQuery method 2 times for each of the named queries, it does not help me, since the max results would increase on each call. How do I handle the same on the Java side? Please let me know. I already have the UI ready to handle.

I once had a similar issue. Don't use two queries, use one and parameterize it so it use LIMIT , and use for example one variable indicating the number of the current page, and some constant defining how many results will you get on one page.

Then you'll have something like

 LIMIT :offset, :resultsLimit

and you're setting offset to something like (page - 1) * DEFAULT_LIMIT_PER_PAGE , and resultsLimit to DEFAULT_LIMIT_PER_PAGE

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM