Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to sort set created via association in Hibernate  RSS feed

Eric Borisow
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I have been banging my head on the wall for some time trying to figure out how to do this. Here is the setup:

2 tables + association join table

Primary key in each table is an ID field. The Contact_Companies_Map table has two columns. They have foreign key constraints to the Contacts and Companies tables to the id column respectively.

Here is my dilemma. When I retrieve a specific contact, I would like to display the associated companies. However, the companies list is returned sorted by the id column in the association table and not the company name.

Here is part of my .hbm.xml files:

<set name="companies" table="contact_company_map">
<key column="contact_id"/>
<many-to-many column="company_id" class="beans.CompanyBean"/>

<set name="contacts" table="contact_company_map">
<key column="company_id"/>
<many-to-many column="contact_id" class="beans.ContactBean"/>

I retrieve the companies using the following piece of code once I retrieve the Contact object:

Hibernate.initialize( contact.getCompanies());
Set companies = contact.getCompanies();

Everything works well, except not being sorted by company_name. I found that the following code worked:

List companyList = sess.createFilter(companies, "order by company_name" ).list();

but I have already started using a Set in my bean and not a List. Can someone help give me some guidance here on what I should do?

Avinash Rawana
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

How can I sort / order collection elements?

There are three different approaches:

1. Use a SortedSet or SortedMap, specifying a comparator class in the sort attribute or <set> or <map>. This solution does a sort in memory.

2. Specify an order-by attribute of <set>, <map> or <bag>, naming a list of table columns to sort by. This solution works only in JDK 1.4+.

3. Use a filter session.createFilter( collection, "order by ...." ).list()

I found that in the FAQ. This question had been puzzling me as well.
[ March 24, 2006: Message edited by: Avinash Rawana ]
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!