2
votes

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.

2

2 Answers

2
votes

Just add this

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

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

and remove this

nameLowerCase formula: 'LOWER(NAME)'

and Enjoy..

3
votes

I think storing the same data in the database is a bad idea. It's better to do it this way:

class Item {
    static transients = ['nameLoweCase']
    String name

    String getNameLowerCase(){
       name.toLowerCase() 
    }

    static constraints = {
       name blank: false
    }
}

And in the controller:

class SomeController{
     def show(Long id){
        def item = Item.get(id)
        item.nameLowerCase // name in lower case
     }
}

'transient' defines a list of property names that should not be persisted to the database (more about it).