title: Ordering By Mapping Table Value in Hibernate
body: <p>I have a @ManyToMany mapping where the table self-references through a mapping table, and we want to order on an order id in the actual mapping table, but are finding it difficult to configure this.</p>
  
  <p>We could perform it in hibernate xml, so it is natural to assume the support is there in JPA annotations. Does anybody know how we can order on a value in the mapping table?</p>
  
  <p>The table is:</p>
  
  <pre><code>wap_site_components
  
  intid
  strname
  intcomponentdef
  dtmcreated      
  intcustomer 
  </code></pre>
  
  <p>and the mapping table that self-references is:</p>
  
  <pre><code>wap_site_component_relations
  
  intid     
  intparent (references intid in wap_site_components)
  intchild  (references intid in wap_site_components)
  intorder (this is the value we want to order the collection on)
  </code></pre>
  
  <p>In Hibernate Annotations we have: </p>
  
  <pre><code>@ManyToMany (fetch = FetchType.LAZY, cascade = CascadeType.ALL)
  @JoinTable (name = "wap_site_component_relations", 
      joinColumns = {@JoinColumn (name = "intparent", referencedColumnName = "id") }, 
      inverseJoinColumns = {@JoinColumn (name = "intchild", referencedColumnName = "id") })
  public Set&lt;WapComponent&gt; getChildren() {
      return children;
  }
  </code></pre>
  
  <p>This is how we performed it in hibernate xml:</p>
  
  <pre><code>        &lt;set
            name="children"
            table="wap_site_component_relations"
            lazy="true"
            cascade="none"
            sort="unsorted"
            order-by="intorder"
            mutable="false"
          &gt;
            &lt;cache 
              usage="read-only" 
            /&gt;
  
            &lt;key
              column="intparent"
            &gt;
            &lt;/key&gt;
  
            &lt;many-to-many
              class="se.plusfoursix.im46.data.wap.WapComponent"
              column="intchild"
              outer-join="auto"
             /&gt;
  
         &lt;/set&gt;
  </code></pre>
  
  <p>So we want to use the @OrderBy tag but cannot reference the intorder value in the mapping table. Any ideas? Thanks.</p>
  
  <p>(We have tried an @OrderBy(intorder) over the children collection in code but that hasn't worked out for us)</p>