I have two Objects, Entries and Samples. Each entry has an associated set of Samples, and each Sample has a vote associated with it. I need to query the database for all E开发者_开发问答ntries, but for each Entry I need the associated set of Samples sorted according to their vote attribute:
public Class Entry{
Set<Sample> samples;
}
public Class Sample{
int vote;
}
I tried to sort the list of Samples after I had performed the query, but this turned out to be a mess because can't cast between a hibernate set and a java set. Can somebody help me alter my query to have the result I need?
List<Entry> entries = jpaTemplate.find("from Entry");
I found an embarrassingly simple solution to this problem. There is an @OrderBy JPA annotation that works perfectly:
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@OrderBy("votes DESC")
public Set<Sample> getSamples() {
return samples;
}
According to the hibernate faq: There are three different approaches:
Use a SortedSet or SortedMap, specifying a comparator class in the sort attribute or or . This solution does a sort in memory.
Specify an order-by attribute of , or , naming a list of table columns to sort by. This solution works only in JDK 1.4+.
Use a filter session.createFilter( collection, "order by ...." ).list()
精彩评论