Archive

Archive for August, 2009

Java – The Ordered Set

August 19th, 2009 admin No comments

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:


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!!

Categories: j2ee Tags: