views:

40

answers:

3

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<TaskNote> notes;
public Set<TaskNote> getNotes() {return notes;}
public void setNotes(Set<TaskNote> notes) {this.notes = notes;} 
+1  A: 

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.

Jeff
+2  A: 

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.

Affe
+2  A: 

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.

oedo
My answer was a full solution. You don't need to specify @OrderBy to achieve order, you can specify it in how you retrieve data. I'd argue that this is more flexible, since @OrderBy is not dynamic.
Jeff
ok fair enough, i guess the wording of OP's question seems to me to indicate they want to use annotations to always order in a specific way.
oedo