Explain belongsTo in Grails

Sanjeev picture Sanjeev · Feb 6, 2014 · Viewed 8.6k times · Source

From the Grails belongsTo documentation, what is the use of

   class Book {
    static belongsTo = Author
}

What is the impact of cascading operations on Book, when CRUD operations performed on Author?

EDIT:

Thanks for your responses, may be i didn't specify my question correctly. I would like to know the difference between

 static belongsTo [author:Author]

vs

 static belongsTo = Author

Answer

grantmcconnaughey picture grantmcconnaughey · Feb 6, 2014

belongsTo is helpful if you need a reference back to the owning object. In this case it is likely that an Author has many Books. But maybe you're using a book object and want to mention that book instance's Author. That is a good way to get it.

As far as CRUD goes, deleting or updating the book will not do anything to the Author, but deleting the Author will delete the Book. If you don't add belongsTo then there will be no cascading saves/updates/deletes, you will have to do it manually.

Example:

def a = new Author(name: 'J.K. Rawling')
a.addToBooks(new Book(title: 'Harry Potter 1'))
a.addToBooks(new Book(title: 'Harry Potter 2'))
a.save()   // Saves author and book instances

a.delete() // Author and both books are deleted

Edit:

The OP updated their question, and I'm honestly not sure what the answer would be. Hopefully Burt Beckwith will show up soon! Good question, OP.