title: Is it possible to order by a composite key with JPA and CriteriaBuilder
body: <p>I would like to create a query using the JPA CriteriaBuilder and I would like to add an <code>ORDER BY</code> clause. This is my entity:</p>
  
  <pre><code>@Entity
  @Table(name = "brands")
  public class Brand implements Serializable {
  
      public enum OwnModeType {
          OWNER, LICENCED
      }
  
      @EmbeddedId
      private IdBrand id;
      private String code;
      //bunch of other properties
  }
  </code></pre>
  
  <p>Embedded class is:</p>
  
  <pre><code>@Embeddable
  public class IdBrand implements Serializable {
  
      @ManyToOne
      private Edition edition;
      private String name;
  }
  </code></pre>
  
  <p>And the way I am building my query is like this:</p>
  
  <pre><code>CriteriaBuilder cb = em.getCriteriaBuilder();
  CriteriaQuery&lt;Brand&gt; q = cb.createQuery(Brand.class).distinct(true);
  Root&lt;Brand&gt; root = q.from(Brand.class);
  if (f != null) {
      f.addCriteria(cb, q, root);
      f.addOrder(cb, q, root, sortCol, ascending);
  }
  return em.createQuery(q).getResultList();
  </code></pre>
  
  <p>And here are the functions called:</p>
  
  <pre><code>public void addCriteria(CriteriaBuilder cb, CriteriaQuery&lt;?&gt; q, Root&lt;Brand&gt; r) {
  }
  
  public void addOrder(CriteriaBuilder cb, CriteriaQuery&lt;?&gt; q, Root&lt;Brand&gt; r, String sortCol, boolean ascending) {
      if (ascending) {
          q.orderBy(cb.asc(r.get(sortCol)));
      } else {
          q.orderBy(cb.desc(r.get(sortCol)));
      }
  }
  </code></pre>
  
  <p>If I try to set <code>sortCol</code> to something like <code>"id.name"</code> I get the following error:</p>
  
  <blockquote>
    <p>javax.ejb.EJBException: java.lang.IllegalArgumentException: Unable to resolve attribute [id.name] against path</p>
  </blockquote>
  
  <p>Any idea how I could accomplish that? I tried searching online, but I couldn't find a hint about this... Also would be great if I could do a similar <code>ORDER BY</code> when I have a <code>@ManyToOne</code> relationship (for instance, <code>"id.edition.number"</code>)</p>