Explain owned by Grails

From the Grails documentation belongs to what is used

class Book { static belongsTo = Author } 

What is the effect of cascading operations on a book when CRUD operations are performed in Author?

EDIT:

Thanks for your answers, maybe I did not ask my question correctly. I would like to know the difference between

  static belongsTo [author:Author] 

vs

  static belongsTo = Author 
+6
source share
5 answers

belongsTo is useful if you need a link back to the owner object. In this case, it is likely that Author has many Book s. But perhaps you are using a book object and want to mention this instance of Author . This is a good way to get it.

Regarding CRUD, deleting or updating a book will not do anything with Author , but removing Author will delete Book . If you do not add belongsTo , then there will be no cascading save / update / delete, you will have to do it manually.

Example:

 def a = new Author(name: 'JK 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 his question, and I honestly don't know what the answer will be. Hopefully Bert Beckwith is coming soon! Good point, OP.

+9
source

Both methods offer cascading effects in the same way. Their only difference is that in the first case, you will have a link to the author in the Book object, while you are not in the latter. I.e:

You can say Book b = new Book(); b.author Book b = new Book(); b.author in the second case.

+1
source

In addition to Grantmc:

belongs to the practical value of the built-in kind of relationship between them, so all operations are automatically cascaded when it is used.

Without participation. You need to manually define cascades (if you want any cascades you have for your relativity)

0
source

It seems to me that this is embarrassing and takes extra effort, since I can achieve the same result with respect to relationships, just using one hasMany and ignore belongsTo , but you need to make let say Author a class variable in Book Domain / class

 class Author { static hasMany = [books: Book] } class Book { Author author //can have only one Instance to be saved at a time } 

But the reason you use belongsTo is because the data is respected when you insert data, following the path from Author to Book , while maintaining the perfect way to manage relationships using belongsTo . Unless you specify it as a class variable or use belongsTo , Grails will not understand the relationship between the two methods.

0
source

According to doc , the same thing is to do what belongs to: toTo = [author: Author], what belongs toTo = Autor, both will create a property called the author, referencing the object "father".

Saludos

0
source

All Articles