I’ve noticed a funny quirk in Hibernate 3. I have a table Product and this product can have say several Images. In the mappings I specify Product.images dependency as fetch=EAGER, i.e. I request a JOIN on Image table. If a product has 3 images, then the ResultSet will contain 3 almost identical records differing just by the content of joined Image record. It is natural to expect Hibernate to merge these 3 records into a single Product (they have the same id column) and 3 Image children. However this is not the case if you are using the DetachedCriteria:
DetachedCriteria criteria = DetachedCriteria.forClass(entityClass);
criteria = criteria.addOrder(ascending ? Order.asc(orderBy) : Order.desc(orderBy));
List<T> list = getHibernateTemplate().findByCriteria(criteria);The resulting list will contain 3(!!!) Product objects with the same id :) each having one child Image.
I had to rewrite the search query like this:
List find = getHibernateTemplate().find("from " + entityClass.getSimpleName()
+ " order by " + orderBy + " " + (ascending ? " asc " : " desc"));This one groups results correctly.
First published on the old anydoby.com blog on 2008-04-09.