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.
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!
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:
@Sort
javadocs If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With