Using hibernate with annotations, i want a one-many relationship to be sorted by the 'created' field on the 'many' table.
So far i've got this, which always ends up in a random order:
// The notes
@OneToMany
@JoinColumn(name="task_id")
Set<TaskN开发者_JAVA百科ote> notes;
public Set<TaskNote> getNotes() {return notes;}
public void setNotes(Set<TaskNote> notes) {this.notes = notes;}
since neither answer gave you the full solution :
@OneToMany
@JoinColumn(name="task_id")
@OrderBy("created")
List<TaskNote> notes;
public List<TaskNote> getNotes() {return notes;}
public void setNotes(List<TaskNote> notes) {this.notes = notes;}
Set
is unordered, so use List
instead, and you need the @OrderBy
annotation too.
Use a List instead of a Set. A List preserves order, a Set doesn't. Using a List, the order of the elements will match whatever you specify for your ORDER BY in HQL or using Criteria.
You have two options, you can either
@OrderBy("created")
which will do what you would expect in SQL.
You can also @Sort
which allows you to specify an arbitrary comparator implementation, if you want to sort in memory for some reason.
Edit: unpredictable iteration order is an implementation detail of HashSet, it's not part of the contract of the Set interface. Hibernate will happily use LinkedHashSet when you use XML mapping and specify ordering on a set. I assumed it does the same when you use the annotation, apologies if that was incorrect.
精彩评论