Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort hibernate collection when retrieving from database

Tags:

java

hibernate

I have an object Foo with a list of Bar. Is there a way I can set up my class so that getBars() will return a List that has been sorted with Collections.sort? In other words, I would like to run Collections.sort when the list is first populated. Presently, I call sort when I retrieve the collection, which may be redundant and is easily forgotten.

like image 634
schmmd Avatar asked Feb 22 '11 17:02

schmmd


2 Answers

Are you using J2EE-style mappings with Hibernate XML files, or are you using JPA-annotated JavaBeans?

If you're using JPA, you can use the @OrderBy annotation to let the database sort the collection for you. You could also use @Sort to do it on the Java side.

Last, if you're writing HQL - say, in a @NamedQuery - you can use the ORDER BY clause.

Lots of ways to do it!

like image 76
Matt Ball Avatar answered Sep 20 '22 04:09

Matt Ball


I think if you annotate the property with @Sort it gets sorted automatically

You've also got the option to specify a custom Comparator class:

@Sort(comparator=MyComparator.class, type=SortType.COMPARATOR)

Reference:

like image 27
Sean Patrick Floyd Avatar answered Sep 21 '22 04:09

Sean Patrick Floyd