我有以下映射:
@RequestMapping(value = "/client/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Client>> listAll(
@RequestHeader(value = "username", required = true) String username,
@RequestHeader(value = "api_key", required = false) String apiKey) {
if (!authenticationService.validate(username, apiKey)){
throw new UnauthorizedUserException();
}
List<Client> clients = clientService.findAll();
return new ResponseEntity<List<Client>>(clients, HttpStatus.OK);
}
我的问题是可能会返回数千条记录。我如何最好地设计此映射以支持客户端上的分页?
最佳答案
您可以创建一个类作为您的输入对象或请求,它接受所有参数,然后如果您必须使用这些参数来应用分页。请检查以下内容:
public class ClientSearchCriteria {
private String username;
private String apikey;
private Long pageNo;
private Long recordsPerPage;
/*getters and setters*/
}
在您的数据库调用中(如果您使用 hibernate 和条件):使用以下方法 -
public Criteria applyPaginationCriteria(ClientSearchCriteria searchCriteria){
Long recordsPerPage = searchCriteria.getRecordsPerPage();
if (recordsPerPage >= 0L) {
criteria.setFirstResult((int) (searchCriteria.getPageNo() * recordsPerPage - recordsPerPage));
criteria.setMaxResults(recordsPerPage.intValue());
}
return criteria;
}
或者,如果不是 hibernate 调用,您可以使用 sql 查询来检索结果(如上面的 HQL 查询),然后将其传递给您的服务调用。
关于java - 如何对 GET 请求中返回的数据进行分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41257594/