Hibernate: order multiple one-to-many relations

Posted by Markos Fragkakis on Stack Overflow See other posts from Stack Overflow or by Markos Fragkakis
Published on 2010-04-12T13:06:48Z Indexed on 2010/04/12 13:43 UTC
Read the original article Hit count: 462

Filed under:
|
|
|
|

I have a search screen, using JSF, JBoss Seam and Hibernate underneath. There are columns for A, B and C, where the relations are as follows:

A (1< -- >) B (1< -- >) C

A has a List< B > and B has a List< C > (both relations are one-to-many).

The UI table supports ordering by any column (ASC or DESC), so I want the results of the query to be ordered. This is the reason I used Lists in the model.

However, I got an exception that Hibernate cannot eagerly fetch multiple bags (it considers both lists to be bags). There is an interesting blog post here, and they identify the following solutions:

  1. Use @IndexColumn annotation (there is none in my DB, and what's more, I want the position of results to be determined by the ordering, not by an index column)
  2. Fetch lazily (for performance reasons, I need eager fetching)
  3. Change List to Set

So, I changed the List to Set, which by the way is more correct, model-wise.

  • First, if don't use @OrderBy, the PersistentSet returned by Hibernate wraps a HashSet, which has no ordering.
  • Second, If I do use @OrderBy, the PersistentSet wraps a LinkedHashSet, which is what I would like, but the OrderBy property is hardcoded, so all other ordering I perform through the UI comes after it.

I tried again with Sets, and used SortedSet (and its implementation, TreeSet), but I have some issues:

  1. I want ordering to take place in the DB, and not in-memory, which is what TreeSet does (either through a Comparator, or through the Comparable interface of the elements).
  2. Second, I found that there is the Hibernate annotation @Sort, which has a SortOrder.UNSORTED and you can also set a Comparator. I still haven't managed to make it compile, but I am still not convinced it is what I need.

Any advice?

© Stack Overflow or respective owner

Related posts about hibernate

Related posts about order