title: Handling dynamic queries with Spring
body: <p>The problem I'm trying to solve here is, filtering the table using dynamic queries supplied by the user.
  Entities needed to describe the problem:</p>
  <p>Table: <code>run_events</code></p>
  <p>Columns: <code>user_id, distance, time, speed, date, temperature, latitude, longitude</code></p>
  <p>The problem statement is to get the run_events for a user, based on a filterQuery.
  Query is of the format,</p>
  <pre><code>((date = '2018-06-01') AND ((distance &lt; 20) OR (distance &gt; 10))
  </code></pre>
  <p>And this query can combine multiple fields and multiple AND/OR operations.</p>
  <p>One approach to solving this is using hibernate and concatenating the filterQuery with your query.</p>
  <pre><code>&quot;select * from run_events where user_id=:userId and &quot;+filterQuery;
  </code></pre>
  <p>This needs you to write the entire implementation and use sessions, i.e.</p>
  <pre><code>        String q = select * from run_events where user_id=:userId and &quot;+filterQuery;
  
          Query query = getSession().createQuery(q);
          query.setParameter(&quot;userId&quot;, userId);
   
  
          List&lt;Object[]&gt; result = query.list();
          List&lt;RunEvent&gt; runEvents = new ArrayList&lt;&gt;();
          for(Object[] obj: result){
              RunEvent datum = new RunEvent();
              int index = -1;
              datum.setId((long) obj[++index]);
              datum.setDate((Timestamp) obj[++index]);
              datum.setDistance((Long) obj[++index]);
              datum.setTime((Long) obj[++index]);
              datum.setSpeed((Double) obj[++index]);
              datum.setLatitude((Double) obj[++index]);
              datum.setLongitude((Double) obj[++index]);
              datum.setTemperature((Double) obj[++index]);
              runEvents.add(datum);
          }
  
  </code></pre>
  <p>This just doesn't seem very elegant and I want to use the @Query annotation to do this i.e.</p>
  <pre><code> @Query(value = &quot;select run_event from RunEvent where user_id = :userId and :query order by date asc&quot;)
      List&lt;RunEvent&gt; getRunningData(@Param(&quot;userId&quot;) Long userId,
                                        @Param(&quot;query&quot;) String query,
                                     );
  </code></pre>
  <p>But this doesn't work because query as a parameter cannot be supplied that way in the query.</p>
  <p>Is there a better, elegant approach to getting this done using JPA?</p>
  <p>Using Specifications and Predicates seems very complicated for this sort of a query.</p>