17
votes

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.

3
There is an old but unresolved request for this: jira.grails.org/browse/GRAILS-5306 - GreenGiant

3 Answers

31
votes

Here is a Groovy solution. Still essentially implementing a Comparator though.

list.sort { map1, map2 -> map1.rowNum <=> map2.rowNum ?: map1.position <=> map2.position }
9
votes

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

0
votes

You can use String.format if you know max length. I assumed max 10 lenght:

list.sort { String.format('%010d%010d', it.rowNum, it.position) }