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
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
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)
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 ignorebelongsTo
, but you need to make let sayAuthor
class variable inBook
Domain/ClassBut the reason you use
belongsTo
is it is enforcing the relationship to follow the path fromAuthor
toBook
when inserting data, keeping a perfect way of governing the relationship usingbelongsTo
. If you don't specify it as class variable or usebelongsto
Grails is not going to understand the two way relationship at all.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.belongsTo
is helpful if you need a reference back to the owning object. In this case it is likely that anAuthor
has manyBook
s. But maybe you're using a book object and want to mention that book instance'sAuthor
. 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 theAuthor
will delete theBook
. If you don't addbelongsTo
then there will be no cascading saves/updates/deletes, you will have to do it manually.Example:
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.