6

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;
 }
}
Daniel Newtown
  • 2,873
  • 8
  • 30
  • 64
  • On which bases are you trying to sort? It seems you are trying to sort a class not an Integer or String?? – Noman Rafique Jun 15 '15 at 06:32
  • I don't use Hibernate, but the javadocs that note it as deprecated have a comment, "Use [SortComparator](https://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/annotations/SortComparator.html) or [SortNatural](https://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/annotations/SortNatural.html) instead depending on need." Sounds like your need is for the SortComparator. – yshavit Jun 15 '15 at 06:33
  • I need to sort Offer objects of offers collection based on values their sort fields. – Daniel Newtown Jun 15 '15 at 06:33

1 Answers1

18

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47