title: JPA Repository filter using Java 8 Predicates
body: <p>I had a requirement in one of my interview tests using Spring Boot where I had to create an endpoint that accepts a bunch of optional request params and then returns a list of cars based on these parameters like car model, license plate, engine type, manufacturer, driver, the company it was rent to etc etc. And car, driver and manufacturer are all separate entities.</p>
  
  <p>I implement this functionality in JPARepository with a single JPQL query implementing LEFT JOINS and filter in where clause like licensePlate = licensePlateParameter OR licensePlatParameter is null etc.</p>
  
  <p>The solution was working however the interviewer said the solution was scalable and maintainable. I should have implemented it using predicates. Can someone show me an example how could I implement such functionality using predicates that is easier to maintain? Some examples with code would be greatly appreciated.</p>
  
  <p>I thought I was smart by catering both the optional parameters and found records with in a single call by checking if the parameter is null or not. Another question related to that I have in mind is it really a good practice to get all the records from DB and then filter it using predicates? Also how to we filter when we have multiple objects/entities involved, predicates can be created for a single type. </p>
  
  <pre><code>@Query("SELECT d FROM Driver d LEFT JOIN d.car c WHERE (d.name = :name OR :name is null) "
              + "and (c.licensePlate = :licensePlate OR :licensePlate is null) "
              + "and (c.rating = :rating OR :rating is null) " and so on
  
      List&lt;Driver&gt; findByAttributes(@Param("name") String name, 
              @Param("licensePlate") String licensePlate,
              @Param("rating") Integer rating,
              and so on);
  </code></pre>