Search code examples
sqlgrailsgrails-orm

How to set a derived property to lower case in Grails/GORM?


This is a newbie question -- thank you for your help. I wanted to set a derived property to lower case in my domain model. Did some search (http://grails.org/doc/latest/guide/GORM.html#ormdsl plus some other) and I thought the following would work (note: nameLowerCase formula: 'LOWER(NAME)') ...

class Item {
    String name
    String nameLowerCase

    static constraints = {
        name(blank: false)
        nameLowerCase(blank: false, unique: true)
    }

    static mapping = {
        nameLowerCase formula: 'LOWER(NAME)'
        sort nameLowerCase: "asc"
    }
}

However, when I do ...

new Item(name: 'A').save(failOnError: true)
new Item(name: 'c').save(failOnError: true)
new Item(name: 'B').save(flush: true, failOnError: true)

println Item.list().nameLowerCase

I was expecting it to print [a, b, c] (turning to lower case in addition to the sorting), but it prints [null, null, null], and I am unable to figure out why.

What am I doing wrong? Or, is there any other way I can achieve the lower case in my domain class itself for nameLowerCase irrespective of what is passed for the name (other than using the formula in mapping)? Any help will be appreciated.


Solution

  • Just add this

    def beforeInsert() {
        nameLowerCase = name.toLowerCase()
    }
    
    def beforeUpdate() {
        nameLowerCase = name.toLowerCase()
    }
    

    and remove this

    nameLowerCase formula: 'LOWER(NAME)'
    

    and Enjoy..