Search code examples
grailsgrails-orm

Override getter and setter in grails domain class for relation


How to override getter and setter for field being a relation one-to-many in grails domain class? I know how to override getters and setters for fields being an single Object, but I have problem with Collections. Here is my case:

I have Entity domain class, which has many titles. Now I would like to override getter for titles to get only titles with flag isActive equals true. I've tried something like that but it's not working:

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'
    }
}

Thank You for your help.


Solution

  • Need the reference 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
        }
    }