6

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.

kpater87
  • 1,190
  • 12
  • 31
  • What error do you get? – dmahapatro Jun 18 '13 at 13:31
  • 1
    Interested in reasoning behind this requirement, why not use separate method for it? As now if you will need to add capability to retrieve all titles then you will have to write separate method which could be supported by default. – Ivar Jun 18 '13 at 13:31
  • Note this: http://grails.1312388.n4.nabble.com/Customized-getter-td1380706.html#a1380709. In short, make sure that your setters and getters don't alter the value or Hibernate will be confused. – Charles Wood Oct 10 '14 at 16:19

1 Answers1

6

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
    }
}
dmahapatro
  • 49,365
  • 7
  • 88
  • 117
  • Setter should be aslo changed to: public void setTitles(Set s) { titles = s; } And then everything is working fine. – kpater87 Jul 03 '13 at 14:31
  • @kpater87 Correct thanks. I just copied the question from you to show what you actually need to do. Update the question as well. – dmahapatro Jul 03 '13 at 14:39