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 开发者_如何学Gois 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- Hibernate Reference: Sorted Collections
check out the hibernate docs on sorted collections
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/collections.html#collections-sorted.
You can also put another method in your DAO that uses hql to fetch the children, which you can sort via hql.
If the sorting procedure is not based off a single column, I don't think you have any choice but to do the sort yourself. You can add the logic to your domain model...
If you are using XML configuration, you can set order-by
attribute:-
<class name="Foo" table="Foo">
...
<set name="bars" inverse="true" order-by="barName">
<key column="fooId" />
<one-to-many class="Bar" />
</set>
</class>
This way, when you invoke foo.getBars()
, you will get Bar
objects ordered by bar name, in this example.
Sorting the list when you select from the DB would be a better (let db sort it) choice instead of sorting it after selecting.
精彩评论