How to order by more than one field in Grails?

Viewed 38903

Is there a way to get a list ordered by two fields, say last and first names?

I know .listOrderByLastAndFirst and .list(sort:'last, first') won't work.

10 Answers

This old solution no longer works. Please see mattlary's answer below

You may have to write a custom finder in HQL or use the Criteria Builder.

MyDomain.find("from Domain as d order by last,first desc")

Or

def c = MyDomain.createCriteria()
def results = c.list {
       order("last,first", "desc")
}
MyDomain.findAll(sort: ['first': 'desc','last':'desc'])

works with grails-datastore-gorm:6.0.3

I think a criteria is the best bet, but you did the right thing by attempting a finder first. When retrieving domain objects from GORM, the right order to make the attempt is: dynamic finder, criteria, HQL.

If you were sorting lists on the contents of their items, you would need to implement a comparator which would have some smarts to enable to you decide the sort order based on multiple properties.

Some examples of Groovy-style comparators are shown here

However if the list you are sorting is being returned from a database query, you would be better off sorting it using a CrteriaQuery and sorts on that

I has the same problem. Since my list is not so big, I use groovy sort, as I want to sort on fields of linked domain: CalendarData -> Attraction

def listCalendar (Calendar calendar) {
    respond CalendarData.where {
        calendar == calendar
    }.list().sort{ "$it.attraction.type?:' '$it.attraction.name" }
}
Related