Learn how to augment RestController with the paging and sorting feature.
- [Narrator] One last topic I'd like to cover is how to add paging and sorting to a DTO based API. The first thing we're going to do is add a new method to tourRating repository. That will return a page of tour ratings... find by PkTourId, again passing in Integer, TourId, but then, we're also going to add a Pageable parameter.
Now let's go to our controller, and, our Get method, we're going to add Pageable as a parameter to the Get method. Just like we did in Spring Data rest, the API provides the page, size, and sort URL parameters. Spring Webmvc converts those three parameters, into a Pageable object, then invokes "getAllratingsForTour".
In the rest controller, we pass a Pageable object into the repository method, which queries the database, and returns a page of tourRating objects, so let's do that, call it "tourRatingpage", and what we need to do now is to iterate through these tourRatings that are within this page, convert them to tourRating DTOs, and then return a page of tourRating DTOs.
So I'll have my list of rating DTOs, get the content for that page, and just like we had before, stream it, and map it to tourRating DTOs. Now we want to return a new page, so we call the constructor for PageImpl.
And then we're returning, not a list anymore, but a page. Okay. Let's run it. Now let's create several ratings for Tour one, and then we will page through them, so let's say customer one thought it was bad, customer two thought it was bad, customer three thought it was bad, customer four thought it was okay, customer five thought it was okay, and customer six thought it was okay, and seven liked it a lot.
So let's Get from tourRatings API, where the size of the page is three, and we want page number one, which is the second page, and we're going to sort by score ascending, so there's our page of just three. At the bottom of the page is Metadata for the client to use when navigating through the pages.
It is possible to embed hypermedia links, but it's beyond the scope of this course on how to do that within a rest controller. Refer to the Spring Hateoas project, to learn how to embed hypermedia into your rest controllers.
- Setting up the project
- Building, deploying, and launch the microservice
- Declaring Spring Data JPA repository interfaces
- Invoking repositories
- Using Spring Data query methods
- Exposing RESTful APIs with Spring Data REST
- Using the /search resource to invoke query methods
- Paging and sorting
- Declaring a new REST controller
- Creating HTTP methods for creating, reading, updating and deleting persistent data.