2

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.

4

2 に答える 2

3

同じデータをデータベースに保存するのは悪い考えだと思います。このようにする方が良いです:

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

    String getNameLowerCase(){
       name.toLowerCase() 
    }

    static constraints = {
       name blank: false
    }
}

そしてコントローラーで:

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

「transient」は、データベースに永続化してはならないプロパティ名のリストを定義します (詳細については)。

于 2013-11-11T18:19:44.383 に答える
2

これを追加するだけ

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

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

これを削除します

nameLowerCase formula: 'LOWER(NAME)'

そして楽しむ..

于 2013-11-11T13:52:38.207 に答える