views:

106

answers:

1

I have a class Person who has a set of Books. It is not meaningful in the particular case to have an ordered or sorted collection.

Say now that I have a search page with a table showing the join of Person and Book. I want to be able to sort the results by fields from both Person AND Book, and then get a List from Hibernate, and iterate over it.

Because the collection is a Set, the ordering of the Books has vanished (PersistentSet of Hibernate wraps a HashSet of Books, which is not ordered).

So, with this approach I cannot have results also ordered by Book fields.

If I change the collection from Set to List, my model is semantically incorrect. There is no meaning for keeping order in the model.

Is there an approach to keep the ordering of Books? Perhaps there is a way for the PersistentSet to wrap a LinkedHashSet (which is ordered), where the order is defined by my search Criteria?

Cheers!

+2  A: 

Hibernate supports mapping a collection as a SortedSet. In your mappings you basically just need to specify an order-by clause. Take a look at this chapter in the reference manual.

matt b
Thanks for the response (+1). Yes, I've seen that. But in the example they have fixed that the ordering is on a certain field. I want that field(s) to be set through the Criteria API, depending on what the user has clicked in the UI.
Markos Fragkakis
You can specify an ordering for results in a Criteria query as well, separate from whatever you specify in the mapping. http://docs.jboss.org/hibernate/stable/core/reference/en/html/querycriteria.html#querycriteria-ordering
matt b
Yes you can, but the unfortunately order-by in the mapping (or @OrderBy) takes precedence, which makes the ordering set by the Criteria useless. Or at least, it comes after the sorting of the order-by of the mapping.
Markos Fragkakis