Search code examples
grailsormgrails-ormhibernate-mappinggrails-domain-class

How to use mappedBy correctly in one to many relation


I am new to grails. I have a problem with one to many relation with my two classes. I have two classes Person and Child as follows

class Child
      {
         String name
         String grade
         Person father
         Person mother
         Person guide

      }

and Person class looks like

         class Person
            {
              String name
              hasMany[child: Child]
            }

How do I use mappedBy here correctly I have looked here . The example given in that link shows mappedBy when the many side has two properties of parent class. how do I use here mappedBy correctly? What difference does it make in the database level? Please help..


Solution

  • You can do it like this

    class Person {
       static hasMany = [childs: Child]
       static mappedBy = [childs:'father'] //or whichever parent you want to use 
    }
    

    As you have only one collection in Person domain, you can map it to just one parent. If you want to map childs for all three parents, you will need three collections in the Person