Bidirectional one to many mapping and importance of mapped by in gorm

Posted By : Shakil Pathan | 09-Jun-2015

Hi,

In this blog, I will  explain you about how to use one to many association in gorm and the difficulties I have faced in bidirectional mapping of this.

For creating one to many mapping you have to define static hasMany in your domain class like:

        class Author {
               String name
               static hasMany = [previousBooks: Book, currentBooks: Book]
         }

        class Book {
              String name
              Author previousAuthor
              Author currentAuthor
        }
 

In the above code we are creating a one to many association between Book and Author class. But it is not bidirectional, because if we try to get previousBooks or currentBooks on Author class object then it will give you the same list of Books because the GORM cannot differentiate which of the two properties on the other end of the association (either previousBooks or currentBooks in the Book class) each one-to-many should be associated with.

The above code will not create any unexpected result of getting previousBooks or currentBooks if we use single Book property in Author class, but when there are multiple properties with the same type its guess can sometimes be wrong.

 

The solution is to define mappedBy which tells the Author class how each association relates to the other side. So we have to define static mappedBy in our Author class like:

class Author {
               String name
               static mappedBy = [previousBooks: "previousAuthor", currentBooks: "currentAuthor"]
               static hasMany = [previousBooks: Book, currentBooks: Book]
         }
 

The mappedBy property is a simple map of property name pairs, where the key is the name of an association property in the current domain class and the value is the name of an association property in the domain class on the other side of the association (which may be itself). The examples above should clarify this.

Hope it helps!

 

Thanks 

About Author

Author Image
Shakil Pathan

Shakil is an experienced Groovy and Grails developer . He has also worked extensively on developing STB applications using NetGem .

Request for Proposal

Name is required

Comment is required

Sending message..