title: Spring JPA Specification with Sort
body: <p>I am using Spring JPA.</p>
  
  <p>To be more precise I am using a Repository which extends <code>JpaRepository</code> and <code>JpaSpecificationExecutor</code> because I require pagination, filtering and sorting.</p>
  
  <p>Now I have the pagination and filtering all working just fine, but I cannot get sorting to work as well.</p>
  
  <p>I notice with some disappointment that <code>JpaSpecificationExecutor</code> has <code>findAll()</code> methods:</p>
  
  <pre><code>findAll(Specification, Pageable);
  findAll(Specification, Sort);
  </code></pre>
  
  <p>But the one I need:</p>
  
  <pre><code>findAll(Specification, Pageable, Sort); //or something like this
  </code></pre>
  
  <p>does not exist!</p>
  
  <p>So, Plan B, include Sorting in the Specification.</p>
  
  <p>With the help of the Accepted Answer to this question: <a href="https://stackoverflow.com/questions/37203878/jpaspecificationexecutor-join-order-by-in-specification">JpaSpecificationExecutor JOIN + ORDER BY in Specification</a> I put together the following:</p>
  
  <pre><code>private Specification&lt;MainEntity&gt; matches() {
      return new Specification&lt;MainEntity&gt;() {
  
          public Predicate toPredicate(Root&lt;MainEntity&gt; root, CriteriaQuery&lt;?&gt; query, CriteriaBuilder cb) {
  
              List&lt;Predicate&gt; predicates = new ArrayList&lt;Predicate&gt;();
  
              //Attempt to sort by Surname, has no effect
              query.orderBy(cb.asc(root.get("surname")));
  
              //add string filters
              for (String field : stringFilterMap.keySet()) {
                  String valuePattern = stringFilterMap.get(field);
                  predicates.add(cb.like(root.get(field), "%"+valuePattern+"%"));
              }
  
              //...snip...
  
              return cb.and(predicates.toArray(new Predicate[predicates.size()]));
          }
      };      
  }
  </code></pre>
  
  <p>Where <code>springFilterMap</code> is an instance field, <code>Map&lt;String,String&gt;</code> whose keys are field names and values are filters values.</p>
  
  <p>Above you will see my attempt to order by Surname, but this seems to have no effect.</p>
  
  <p>What am I doing wrong; &amp; how can I achieve Sorting along with Pagination and Filtering?</p>