Manually merge changes for GRAILS-9644

I wrote tests for this originally as part of the HibernateCriteriaBuilderTests but I can't seem to find where those tests went.

This patch is currently in the 2.2.4 release but was missed in the 2.3.x branch.