I just wanted to share this with anyone who is not aware...
Caveat: After reviewing my original post and the comments that follow I had initially elected to change the container tag in the example below from set to list. After thinking about it further I've returned the tag to 'set', since this is after all what I was trying to illustrate in the first place (although understanding the risk of using set should be understood). Granted, a list probably should have been used, but this was a solution to a problem relating to an existing system that I'm currently working on. I apologize if it offends your senses, it sort of does mine too, but the tests do pass and the code does work as expected. Hopefully others facing similar constraints may find it of use in any case. 
We are using hibernate of my current project, but this should be the same for nHibernate. In any case, we ran into a situation where we needed to ensure that a collection (Set) on a class that we were mapping needed to ensure the order of list items when used in the middle tier. The class had a sequenceNumber field that was used to indicate ordinality in the Set. The knee-jerk solution proposed was to modify the class to support sorting, but it was work that no one wanted to pick up so the code stayed broken.
I, being industriously lazy, didn't want to do it either but wanted it done none the less. I had never set the order-by in the hbm configs before but figured this would be as good a reason to use it as any. So I made one simple change to our mapping file and the broken unit tests magically started passing. Here's a code example:
<set
name="myCollectionOfThings"
lazy="true"
inverse="true"
order-by="SEQUENCE_NUMBER ASC"
>
<key>
<column name="THING_HOLDER_FK" />
</key>
<one-to-many
class="blah.blablah.ThingHolder"
/>
</set>
It's the "order-by" attribute in the "set" tag is what is used to define the default OrderBy behavior. The contents are straight SQL that get's tagged on the end of the rendered prepare statement that is executed against the database.
Hope that's of use!
Posted
Jun 05 2008, 04:23 PM
by
jlockwood