Search code examples
grailsgrails-orm

How to persist data in a sorted order in GORM


This is a newbie question, any help will be appreciated. I have a class Item as follows.

class Item {
    String name
    // other properties ...

    static constraints = {
        name(blank: false, unique: true)
        // other constraints ...
    }
}

How do I persist the Items in a sorted order in Grails/GORM? Meaning, if I did

new Item(name: 'a').save(flush: true, failOnError: true)
new Item(name: 'c').save(flush: true, failOnError: true)
new Item(name: 'b').save(flush: true, failOnError: true)

println Item.getAll().name

I should get [a, b, c]. Thank you!


Solution

  • Add this in your domain class

    static mapping = {
        sort name: "desc" //"asc"
    }