Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Pageable in @RestController?

I know the Pageable comes from spring-data- domain.

Is there any elegant way to directly use org.springframework.data.domain.Pageable in @RestController?

I tried following.

@RequestMapping(method = RequestMethod.GET,
                path = "pageable",
                produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Pageable> readPageable(@NotNull final Pageable pageable) {
    return ResponseEntity.ok(pageable);
}

The result is not what I expected.

...: ~ $ curl -X GET --header 'Accept: application/json' 'http://localhost:8080/.../pageable?limit=1&offset=1' | python -mjson.tool
...
{
    "offset": 0,
    "pageNumber": 0,
    "pageSize": 20,
    "sort": null
}
like image 488
Jin Kwon Avatar asked Nov 03 '17 02:11

Jin Kwon


People also ask

What is the use of Pageable?

Interface Pageable. The Pageable implementation represents a set of pages to be printed. The Pageable object returns the total number of pages in the set as well as the PageFormat and Printable for a specified page.

How does Spring Pageable work?

Spring Data REST Pagination In Spring Data, if we need to return a few results from the complete data set, we can use any Pageable repository method, as it will always return a Page. The results will be returned based on the page number, page size, and sorting direction.

What is the annotation used for RestController?

Spring RestController annotation is a convenience annotation that is itself annotated with @Controller and @ResponseBody . This annotation is applied to a class to mark it as a request handler. Spring RestController annotation is used to create RESTful web services using Spring MVC.

What is Pageable unpaged ()?

unpaged() . means that invoking repository. findAll(Pageable. unpaged()) should load all entities. What actually happens is that the response contains only 10 result with paging information (total pages, ect)


1 Answers

It should return not Pageable but Page.

public Page<YourEntityHere> readPageable(@NotNull final Pageable pageable) {
    return someService.search(pageable);
}

Pageable is request side which contains what exactly you need. But Page contains results.

See for example the link

like image 146
StanislavL Avatar answered Sep 22 '22 11:09

StanislavL