My task is to make an advanced search with Spring Data REST. How can I implement it?
I managed to make a method to do a simple search, like this one:
public interface ExampleRepository extends CrudRepository<Example, UUID>{
@RestResource(path="searchByName", rel="searchByName")
Example findByExampleName(@Param("example") String exampleName);
}
This example works perfectly if I have to go simply to the url:
.../api/examples/search/searchByName?example=myExample
But what I have to do if there are more than one field to search?
For example, if my Example class has 5 fields, what implementation should I have to make an advanced search with all possibiles fileds?
Consider this one:
.../api/examples/search/searchByName?filed1=value1&field2=value2&field4=value4
and this one:
.../api/examples/search/searchByName?filed1=value1&field3=value3
What I have to do to implement this search in appropriate way?
Thanks.
Spring Data Rest has integrated QueryDSL with web support as well which you can use for your advanced search requirement. You need to change your repository to implement QueryDslPredicateExecutor
and things will work out of the box.
Here is a sample from the blog article about the feature:
$ http :8080/api/stores?address.city=York
{
"_embedded": {
"stores": [
{
"_links": {
…
},
"address": {
"city": "New York",
"location": { "x": -73.938421, "y": 40.851 },
"street": "803 W 181st St",
"zip": "10033-4516"
},
"name": "Washington Hgts/181st St"
},
{
"_links": {
…
},
"address": {
"city": "New York",
"location": { "x": -73.939822, "y": 40.84135 },
"street": "4001 Broadway",
"zip": "10032-1508"
},
"name": "168th & Broadway"
},
…
]
},
"_links": {
…
},
"page": {
"number": 0,
"size": 20,
"totalElements": 209,
"totalPages": 11
}
}