Marc
Marc

Reputation: 3243

How to get a sortable set in hibernate

We've generally been using Sets for one to many and many to many collections in hibernate. This has worked fine for until now.

But now we need more and more to do in-memory sorting of child collections at the controller layer because different views need to see child collections in different orders. We can't just specify an order at the entity declaration that works for all our views.

Our issue is that you cannot Collections.sort a Set, and we're afraid of wrapping our Set in a List because that could break our binding (especially in a parent child relation).

So we're thinking of changing all our Set to List in the entities (without an index column), but that seems extreme and I've read of issues with bidirectional one to many and many to many list relations.

Any suggestions?

Upvotes: 1

Views: 657

Answers (4)

Yappie
Yappie

Reputation: 399

I thinks that sorted set can help you. For example:

@OneToMany()
@Sort(comparator = SomeComparator.class, type = SortType.COMPARATOR)
private SortedSet<Item> items= new TreeSet<Item>(SomeComparator.instance());

Implement your own comparator and use it for sorted sets.

Upvotes: 0

ssedano
ssedano

Reputation: 8432

You can define a Formula (in criteria as well) or a SortedSet and implements the comparator. In the definition of the set you can also (in 3.3) define a order-by element (SQL).

Example:

Formula: Made in DBMS for a particular relation.
<many-to-one name="homeAddress" class="Address" insert="false" update="false">
    <column name="person_id" not-null="true" length="10"/> 
    <formula>'ORDER BY LENGTH(homeAddress)'</formula>   
</many-to-one>

Formula in Criteria: Made in DBMS.
sortedUsers = s.createFilter( group.getUsers(), "order by this.name" ).list();

Sorted: Made in Java and application wide for a particular relation.
<map name="holidays" sort="my.custom.HolidayComparator">
    <key column="year_id"/>
    <map-key column="hol_name" type="string"/>
    <element column="hol_date" type="date"/>
</map>

Order-by clause: Made in DBMS and application wide for a particular relation.
<set name="aliases" table="person_aliases" order-by="lower(name) asc">
    <key column="person"/>
    <element column="name" type="string"/>
</set>

Upvotes: 0

Impiastro
Impiastro

Reputation: 858

You can let your set objects implement the Comparable<> interface.

In this way using the compareTo function (that you must implement) you can specify an order for your sets.

Hibernate, initializing the set, will use the order specified in the compareTo function.

Upvotes: 1

flash
flash

Reputation: 6820

Google Collections has a ImmutableSortedSet, maybe that could help.

Upvotes: 0

Related Questions