title: Java Spring REST API Handling Many Optional Parameters
body: <p>I'm currently messing around with a Spring Boot REST API project for instructional purposes. I have a rather large table with 22 columns loaded into a MySQL database and am trying to give the user the ability to filter the results by multiple columns (let's say 6 for the purposes of this example).</p>
  
  <p>I am currently extending a Repository and have initialized methods such as findByParam1 and findByParam2 and findByParam1OrderByParam2Desc and etc. and have verified that they are working as intended. My question to you guys is the best way to approach allowing the user the ability to leverage all 6 optional RequestParams without writing a ridiculous amount of conditionals/repository method variants. For example, I want to give the user the ability to hit url <em>home/get-data/</em> to get all results, home/get-data?param1=xx to filter based on param1, and potentially, home/get-data?param1=xx&amp;param2=yy...&amp;param6=zz to filter on all the optional parameters. </p>
  
  <p>For reference, here is what the relevant chunk of my controller looks like (roughly). </p>
  
  <pre><code>@RequestMapping(value = "/get-data", method = RequestMethod.GET)
  public List&lt;SomeEntity&gt; getData(@RequestParam Map&lt;String, String&gt; params) {
      String p1 = params.get("param1");
      if(p1 != null) {
          return this.someRepository.findByParam1(p1);
      }
      return this.someRepository.findAll();
  }
  </code></pre>
  
  <p>My issue so far is that the way I am proceeding about this means that I will basically need n! amount of methods in my repository to support this functionality with n equalling the amount of fields/columns I want to filter on. Is there a better way to approach handling this, perhaps where I am filtering the repository 'in-place' so I can simply filter 'in-place' as I check the Map to see what filters the user did indeed populate?</p>
  
  <p>EDIT: So I'm currently implementing a 'hacky' solution that might be related to J. West's comment below. I assume that the user will be specifying all n parameters in the request URL and if they do not (for example, they specify p1-p4 but not p5 and p6) I generate SQL that just matches the statement to LIKE '%' for the non-included params. It would look something like...</p>
  
  <pre><code>@Query("select u from User u where u.p1 = :p1 and u.p2 = :p2 ... and u.p6 = :p6") 
  List&lt;User&gt; findWithComplicatedQueryAndSuch;
  </code></pre>
  
  <p>and in the Controller, I would detect if p5 and p6 were null in the Map and if so, simply change them to the String '%'. I'm sure there is a more precise and intuitive way to do this, although I haven't been able to find anything of the sort yet. </p>