Search code examples
grailsgrails-ormgrails-2.0

Why do we need explicit relationships in grails?


I am a beginner in GRAILS so i am hoping some help on the issue i am facing.

I have read the documentation but i am still vague on the idea of relationships in grails. In grails, you could have 4 types of relationship between domain classes.

1 to 1 1 to many many to 1 many to many

Grails has three constructs to define relationships

static hasMany =
static belongsTo = 
static hasOne = 

My question and dilemma is why do we need these three constructs to define a relation when we could just specify what type of objects each class has that would automatically define relationship between domain classes.

for example

To define many to many i could have two classes designed this way

class Author{

   Set<Book> books

}


class Book{

  Set<Author> authors

}

For 1 to many and many to 1

class Author{

  Set<Book> books

}


class Book{

  String title

}

for one to one

class Author{

  Book book

}


class Book{

  Author author

}

I appreciate it if anyone can give me a clear, easy to understand explanation. Thank you!


Solution

  • Everything you defined there should work fine. You don't have to use any of the other stuff that you mentioned that GORM offers, but there are reasons that you might want to. For example, you can write a class like this:

    class Author{
        Set<Book> books
    }
    

    That is not the same thing as this:

    class Author {
        static hasMany = [books: Book]
    }
    

    When you use hasMany, Grails generates this for you...

    class Author {
        Set<Book> books
    
        def addToBooks(Book b) {
            books.add(b)
            this
        }
    
        def addToBooks(Map m) {
            books.add(new Book(m))
            this
        }
    
        def removeFromBooks(Book b) {
            books.remove(b)
            this
        }
    }
    

    That isn't exactly what is generated, but that is some of the stuff that you might care about.

    There is more to it than is represented there. For example, if the Book has a reference back to the Author, the addToBooks methods will hook that back reference up for you.

    There are other behaviors associated with the other properties you mentioned. For example, the hasOne property switches the direction in which the foreign key points on the persistence model. The belongsTo property enforces cascading of certain events. etc.

    Take a look at the GORM docs at http://grails.org/doc/latest/guide/GORM.html for more information.