Note that there are some explanatory texts on larger screens.

plurals
  1. POOrder by both Parent and then Child using JPA
    text
    copied!<p>Is it possible to order a collection of parent objects by both a parent's property and a child's property?</p> <p>Let's say I have an Entity class that has this bit of code:</p> <pre><code>@OrderBy("age") public List&lt;Father&gt; getFathers() { return fathers; } </code></pre> <p>The Father Entity has an age property which we want to order by ascending age (as shown above).</p> <p>A Father can have a Child. A Child would also have an age property. I would like <code>getFathers()</code> to return a Fathers list such that they are ordered by the Fathers' age and then subsequently the Child's age ascending. </p> <p>If I keep the code above as is, the Fathers would be ordered by their own age correctly but a Father (aged 30) with a 10 year old Child could come before a Father (also aged 30) with a 5 year old Child.</p> <p>I tried doing something like this:</p> <pre><code>@OrderBy("age, child.age") public List&lt;Father&gt; getFathers() { return fathers; } </code></pre> <p>But I would get the following exception:</p> <pre><code>org.hibernate.AnnotationException: property from @OrderBy clause not found: Father.child.age </code></pre> <p><b>Edit:</b> Sorry, let me clarify with a bit more code. The <code>getFathers()</code> is not in the Child entity but in another entity. Let's call it Village:</p> <pre><code>@Entity public class Village { ... @OneToMany(mappedBy = "village", targetEntity = Father.class) @OrderBy("age") public List&lt;Father&gt; getFathers() { return fathers; } } </code></pre> <p>So let's say there is a Village and you can obtain the Fathers that live in this Village. For this example's sake, let's say that a Father for some odd Village rule can only have one child each.</p> <p>So Father would look something like this:</p> <pre><code>@Entity public class Father { private Child child; ... @OneToOne(mappedBy = "father") public Child getChild() { return child; } public void setChild(Child child) { this.child = child; } } </code></pre> <p>So now in the original Village class, I want <code>getFathers()</code> to return all the fathers in order of age, plus, if there are any fathers with the same age, I want them to be then ordered by the age of their child.</p> <p><b>Edit 2:</b> I've also found that I can get the effect of what I want however it can't be the most elegant way of doing it:</p> <pre><code>session.createFilter(village.getFathers(), "order by child.age"); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload