Learn how to Invoke custom Spring Data queries with HTTP GET.
- [Instructor] Every endpoint that Spring Data REST exposes also creates a /search resource. Let's see what happens when we invoke the tourPackages/search GET. Other than the self href, we also see a findByName attribute. Those are the names or the methods we created in TourPackageRepository. Let's try to run findByName as an API called GET on findByName.
This returns an HTTP status code 500 with the message Unable to detect parameter names for query method. Something's missing here. Looks like a little coding is in order because findByName requires a parameter but the API does not know how to associate it. We need to add an annotation to the findByName method. So here we are in TourPackageRepository findByName and I add a Param("name").
Now we need to stop the application and restart it because we made a code change. So now if we invoke just the search resource, we see that there's a ?name listed as a URL parameter. Now let's try to run findByName again and this time provide the Backpack Cal parameter. So name=Backpack%20Cal.
We need to put the %20 because that's the ASCII value for a space and actual spaces are not allowed on URL. So let's run that query. We see that we get back the Backpack Cal tour package. So now that we know how the /search resource works, let's create a TourRepository method with the @Param annotation. So let's open TourRepository. I want to create a method to find all the tours associated with the tour package by the code.
Next restart the application. Go back to Postman. Now let's look at the tours/search resource. As expected, the parameter for the search method are exposed on the API. So let's execute /search/findByTourPackageCode. Put in the California Caln code which is CC.
We get three tours back. While we are looking at the tours, I want to show you Spring Data REST treats entity to entity associations. There is a many to one association between tour package and tours. So the tour package attribute in the JSON response body is a hypermedia link to the tour. That's the hypermedia link. Let's click it. Let's look up that tour package for that tour and it's California Caln.
- 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.