Grails mapping sort on multiple fields :: Groovy sort on multiple map entries

14,039

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

Share:
14,039

Related videos on Youtube

virtualeyes
Author by

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, 2022

Comments

  • virtualeyes
    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
    virtualeyes over 13 years
    just saw have not tested in console -- this will achieve same as HQL find("from SomeDomain as s order by rowNum asc, position desc")?
  • virtualeyes
    virtualeyes over 13 years
    Tasty ;--) 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
    wrschneider over 9 years
    Combinatino of spaceship and Elvis operators makes it super-clean
  • IgniteCoders
    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
    virtualeyes over 9 years
    Thanks, I left Grails not long after posting (4 years ago), might help others though ;-)