tikka
tikka

Reputation: 577

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!

Upvotes: 3

Views: 928

Answers (2)

Ak Goel
Ak Goel

Reputation: 146

Add this in your domain class

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

Upvotes: 1

Daniel Wondyifraw
Daniel Wondyifraw

Reputation: 7723

Presisting doesn't matter but ,what matters the way you retrieve it and you can simply do as follow

println Item.list().sort() 

println Item.list().sort(){ //write your groovy clouser here to sort asc and dec }

Upvotes: 4

Related Questions