Explain belongsTo in Grails

2019-06-17 08:34发布

问题:

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

回答1:

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.



回答2:

Both ways offer cascading effects in the same way. Their only difference is that in the former case you'll have a reference to author in Book object whereas you don't in the latter. That is:

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



回答3:

In addition to Grantmc:

belongsTo practically marks an embedded kind of relation between the two, this is why all operations are cascaded automatically when this is used.

Without belongsTo you need to manually define cascades (if you want anycascades at al for your relatoinship)



回答4:

It seems confusing and extra effort to me it was since I can achieve same result on the relationship by just simply using one hasMany and ignore belongsTo, but you need to make let say Author 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 it is enforcing the relationship to follow the path from Author to Book when inserting data, keeping a perfect way of governing the relationship using belongsTo. If you don't specify it as class variable or use belongsto Grails is not going to understand the two way relationship at all.



回答5:

As the doc says, it is the same to do belongsTo = [author:Author] than belongsTo = Autor, both will create a property called author referencing the "father" object.

Saludos