Wrong OrderBy in generated SQL when using ICriteria, Eager fetching and order by clauses in collection mappings
Description
Consider this scenario: you have 2 classes called 'Item' and 'Tag', Item holds a collection of tags, the relation is mapped as inverse and we have an order-by clause applied to the collection mapping (the tags are ordered by name); we want to fetch a list of Item classes along with all its related Tags (to optimize things) and we want the result to be sorted by some field of the main Item class.
The problem is: performing the query using ICriteria and setting the eager fetch mode on the tags collection you don't get the results with the order you expect (the one you specified in the ICriteria query), instead the order specified in the collection mapping (a <bag> for example) takes over and the object are sorted first for Tag's Name and then for the sort you specified.
This behavior do not happen if you use HQL queries and the correct sorting is applied.
Consider this scenario:
you have 2 classes called 'Item' and 'Tag', Item holds a collection of tags, the relation is mapped as inverse and we have an order-by clause applied to the collection mapping (the tags are ordered by name); we want to fetch a list of Item classes along with all its related Tags (to optimize things) and we want the result to be sorted by some field of the main Item class.
The problem is: performing the query using ICriteria and setting the eager fetch mode on the tags collection you don't get the results with the order you expect (the one you specified in the ICriteria query), instead the order specified in the collection mapping (a <bag> for example) takes over and the object are sorted first for Tag's Name and then for the sort you specified.
This behavior do not happen if you use HQL queries and the correct sorting is applied.
I've made an indept blog post on the subject: http://www.primordialcode.com/blog/post/nhibernate-eager-fetch-order-strange-behavior-icriteria
Attached to this entry you can find a solution to replicate the problem.