Java – The Ordered Set

After doing a bit of Hibernate Development with GWT applications I have come across the same problem a few times when using and executing Hibernate queries.

“Placing persistent objects, found through a Hibernate query, into a Set to avoid duplicates then in nature that set loses any ordering you specified in your query”

Suppose the following query:

<query name="myquery"><![CDATA[
FROM com.company.persistent.Country AS country
LEFT JOIN fetch country.myOtherSet SET
ORDER BY country.countryName ASC ]]>
</query>

We can call this like so:

List countries = (List)getHibernateTemplate().findByNamedQuery("myquery");

That list will unfortunately have duplicates within it – simple because of our left join fetch.

So we decide that if we put the results in a set like so :

if( countries != null && countries.size() > 0 )
{
    countrySet = new HashSet
    countrySet.addAll(countries);
}

It will eradicate any duplicates….but notice in the query we wanted our results ordered by country name. In the original list of countries the order would have been preserved but since we have added the objects to a set we have lost any of that ordering.

This is where the Apache Collections Library can help. If you are using Hibernate I can assume that the Apache Collections library is on your classpath. If so then you can do the following:

List countries = (List)getHibernateTemplate().findByNamedQuery("myquery");
ListOrderedSet countrySet = null;   
if( countries != null && countries.size() > 0 )
{
    countrySet = new ListOrderedSet();
    countrySet.addAll(countries);
}

Using the ListOrderedSet (it extends java.util.Set)from Apache Collections means our ordering is preserved.

Thank you Apache!!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>