开发者

Hibernate Query that Orders an Attribute based on a nested path

开发者 https://www.devze.com 2022-12-17 04:40 出处:网络
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

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:

  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()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号