Grails mapping sort on multiple fields :: Groovy sort on multiple map entries
Solution 1
Here is a Groovy solution. Still essentially implementing a Comparator though.
list.sort { map1, map2 -> map1.rowNum <=> map2.rowNum ?: map1.position <=> map2.position }
Solution 2
Thanks to the link from GreenGiant, we see that the issue is closed as fixed as of version 2.3.
There is also example code:
static mapping =
{ sort([lastname:'asc', name:'asc']) }
It is working for me in 2.4.3
Related videos on Youtube
virtualeyes
Psychologist turned programmer, developing on the JVM with Scala, Akka, Play, and Slick, along with Scala.js in the browser. Currently hacking on the U.S. Hockey Report, an amateur hockey scouting news service.
Updated on May 18, 2022Comments
-
virtualeyes almost 2 years
Stumped on this one. In Grails it seems one cannot define a default sort on multiple columns in domain mapping a la static mapping = { sort 'prop1 desc, prop2 asc' }, or { sort([prop1:'desc', prop2:'asc']) }. Only first column gets sorted, lame.
Similarly, when trying to Groovy sort a Grails findAllBy query on multiple columns, the second sort overrides the first.
def list = [[rowNum:2,position:3],[rowNum:1,position:2],[rowNum:3,position:1]]
list.sort{it.rowNum}.sort{it.position}
Obviously missing the boat on the latter case, the groovy sort. I have seen postings re: implementing comparable, but looking for something more concise if possible.
-
virtualeyes over 13 yearsjust saw have not tested in console -- this will achieve same as HQL find("from SomeDomain as s order by rowNum asc, position desc")?
-
virtualeyes over 13 yearsTasty ;--) confirmed it works; 1-liner is perfectly fine. Would be nice if we could do at mapping level in grails, but that may have to wait for 1.4 and new hibernate. Thanks Peter!
-
wrschneider over 9 yearsCombinatino of spaceship and Elvis operators makes it super-clean
-
IgniteCoders over 9 years@virtualeyes this doesn't sort like HQL, you need to find the collection by your self, and then use sort on it
-
virtualeyes over 9 yearsThanks, I left Grails not long after posting (4 years ago), might help others though ;-)