覆盖grails域类中的getter和setter以获取关系

时间:2013-06-18 13:06:26

标签: grails gorm

如何在grails域类中覆盖字段为一对多关系的getter和setter?我知道如何覆盖作为单个对象的字段的getter和setter,但是我对Collections有问题。这是我的情况:

我有Entity域类,它有很多标题。现在我想覆盖标题的getter,只获得标志为isActive equals true的标题。我尝试了类似的东西,但它不起作用:

class Entity {

    static hasMany = [
        titles: Title
    ]

    public Set<Title> getTitles() {
        if(titles == null)
            return null
        return titles.findAll { r -> r.isActive == true }
    }

    public void setTitles(Set<Title> s) {
        titles = s
    }
}

class Title {
    Boolean isActive

    static belongsTo = [entity:Entity]

    static mapping = {
        isActive column: 'is_active'
        isActive type: 'yes_no'
    }
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

需要参考Set<Title> titles

class Entity {
    Set<Title> titles

    static hasMany = [
        titles: Title
    ]

    public Set<Title> getTitles() {
        if(titles == null)
            return null;
        return titles.findAll { r -> r.isActive == true }
    }

    public void setTitles(Set<Title> s) {
        titles = s
    }
}