title: How to edit a Spring Pageable object?
body: <p>I need to be able to edit a Pageable object, more specifically one of the Sorts.</p>
  
  <p>I have some DTO <code>Member</code> which has a property <code>emailAddress</code>. Unknown to the client, this is information that is gathered by a query from 2 different entities, either <code>Account</code> or <code>Invite</code>. A <code>Member</code> always has either one of these.
  This works well enough, I do a standard JPA query in a repo and gather the required information before transforming it into a DTO.</p>
  
  <p>Now we want to sort on this referenced attribute. That's fine. I can create a query containing something like <code>ORDER BY coalesce(i.emailAddress, a.emailAddress) ASC</code> which works well. If the client doesn't pass any sorting in the Pageable object, I just use this sorting, if the client does pass sorting then I call a different version of the query without this default sort.</p>
  
  <p>But now the client wants to sort on this <code>emailAddress</code> property and the trouble starts. Directly passing the <code>Pageable</code> to the <code>Repository</code> doesn't work because there is no property <code>emailAddress</code>. So I thought no worries! Let's just check in my code if there is a sorting on this property and do a special version of my query depending on the parameters.</p>
  
  <pre><code>if (pageable.getSort().isSorted()) {
      Sort.Order emailAddressOrder = pageable.getSort().getOrderFor("emailAddress");
      if (emailAddressOrder != null) {
          if (emailAddressOrder.getDirection() == Sort.Direction.ASC)
              members = memberRepo.findInProjectDefaultSortAsc(projectId, skipFullName, fullName, pageable);
          else
              members = memberRepo.findInProjectDefaultSortDesc(projectId, skipFullName, fullName, pageable);
      }
      else
          members = memberRepo.findInProject(projectId, skipFullName, fullName, pageable);
  }
  else
      members = memberRepo.findInProjectDefaultSortAsc(projectId, skipFullName, fullName, pageable);
  </code></pre>
  
  <p>Doesn't look superpretty but should work right? Wrong, because the <code>Pageable</code> STILL contains the invalid property <code>emailAddress</code>.</p>
  
  <p>So how do I remove this property? I tried casting it to a <code>PageRequest</code> but even that implementation object isn't writeable. What I did now is this:</p>
  
  <pre><code>PageRequest newPageRequest = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize());
  </code></pre>
  
  <p>And then I pass this new object into the query instead. But that seems a bit error-prone, what if the PageRequest entity gets expanded with additional properties later on, then my object still only copies 2 properties. Is this really the best I can do now?</p>