1

I have a @RequestParam MultiValueMap<String, String> queryParams. The controller takes queryParams from UI end to request JPA Repository and return records from the database.

Is there a way to directly send this MultiValueMap to the repository interface and fetch records based on queryParams?

I have a UserRepository which extends JPARepository<User, Long>.
The controller has a method which takes @RequestParam MultiValueMap<String, String> queryParams as an input and needs to appropriately fetch records from the database and store it in a List<User>.

Ex: if url = /api/users?name=USER123&salary=10000&department=science

I can neither use @PathVariable because there are many such attributes in User which can be used for querying, nor have 1 method for each combination of queryParams.

I need to send the queryParams to fetch exact records matching the query parameters.

public ResponseEntity<List<User>> getSpecificUsers(
    Pageable pageable,
    @RequestParam MultiValueMap<String, String> queryParams
) {}

If there is a way to generate @Query based on the RequestParam query params I am open to use that as well. Any help is appreciated.

Stphane
  • 3,368
  • 5
  • 32
  • 47
Mohammed Idris
  • 768
  • 2
  • 9
  • 26
  • 1
    The JPA criteria API, or QueryDSL, are both designed to do that: generate a query dynamically based on criteria. Note that you could use a Command class, with named and typed properties, instead of a MultiValueMap. – JB Nizet Jul 03 '19 at 10:42
  • Thanks for the edit.I shall take care of the formatting next time. @JBNizet I wanted to know if we could use a `MultiValueMap` instead of String params. And could you please elaborate what is the `Command class` and what you mean by `named` and `typed` properties? – Mohammed Idris Jul 05 '19 at 05:48
  • I cannot have each method for a set of params. i.e., if I have a query like /api/users?name=USER123&salary=10000&department=science I cannot go on writing methods for each of this parameter. I need something which does not make me have to write all the possible query criteria in a class. – Mohammed Idris Jul 05 '19 at 05:57
  • 1
    That's why you would dynamically create the query, in a single method, thanks to the criteria API. A command class with named and types properies wouldbe, in the above example, a class with a property "name" of type String, a property salary of type Integer, and a department of type DepartmentEnum, for example. See https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-modelattrib-method-args – JB Nizet Jul 05 '19 at 06:35
  • I tried using `SpecificationBuilder` and used `findAll(specification)` method and it worked. I have also added a toPredicate method. I followed [REST Query Language.](https://www.baeldung.com/rest-api-query-search-language-more-operations) tutorial to achieve this. Thanks for your timely help. – Mohammed Idris Jul 08 '19 at 09:16

0 Answers0