Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a sorted set of objects based on a specific field?

I need to retrieve a sorted list of objects based on their sort field; Their collection type is SortedSet but the code throws following exception. I also tried to add @Sort annotation as explained in sorted collection section of hibernate documentation but it seems like it is deprecated!

Exception

Caused by: org.hibernate.AnnotationException: A sorted collection must define and ordering or sorting

Code

SortedSet<Offer> offers = new TreeSet<Offer>();

Classes

public class Person {
 @Id
 long id;
 @OneToMany 
 //@OrderBy("sort ASC") <<< If I use this just one offer will be in the collection 
 SortedSet<Offer> offers = new TreeSet<Offer>();
 ...
}

public class Offer implements Comparable<Offer>{

 @Id
 long id;
 String name;
 short sort;
 @Override
 public int compareTo(Offer o) {
    return sort - o.sort;
 }
}
like image 573
Daniel Newtown Avatar asked Dec 06 '22 21:12

Daniel Newtown


1 Answers

You need to specify the column name to be put in the ORDER BY clause

try to add this annotation to the SortedSet

@javax.persistence.OrderBy("sort")

If you need ordering by more than one column, see this answer.

like image 145
Sharon Ben Asher Avatar answered Mar 03 '23 21:03

Sharon Ben Asher