views:

31

answers:

2

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 Entries, 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");
A: 

According to the hibernate faq: There are three different approaches:

  1. Use a SortedSet or SortedMap, specifying a comparator class in the sort attribute or or . This solution does a sort in memory.

  2. Specify an order-by attribute of , or , naming a list of table columns to sort by. This solution works only in JDK 1.4+.

  3. Use a filter session.createFilter( collection, "order by ...." ).list()

Fried Hoeben
thanks for the answer and link. However, I still dont understand how to structure the order by query. I dont want to order the set of results I'm receiving, I want to order the elements in one of the attributes which is a Set
darren
Besides the solution you found yourself options 1 and 3 above also work for a collection properties (e.g. samples in your case). So you could do: session.createFilter(entries.getSamples(), "order by votes").list()
Fried Hoeben
These approaches give you a bit more flexibility: you can use different orderings of the samples in different situations. But if you always want the same ordering, your approach is great
Fried Hoeben
+1  A: 

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;
}
darren