Mcoder
Mcoder

Reputation: 309

Behaviour of belongsTo

What is the difference between

static belongsTo [author:Author]

and

static belongsTo = Author

Lets consider two domain class.

Class Author{
    String name 
}

Class Books{
    String name
    static belongsTo = Author
}

When static belongsTo = Author is kept in Books domain, it have no effects on db. However, static belongsTo = [author : Author] creates a backreference to Author class and also there is author_id column in db. So, what actually using static belongsTo = Author alone does. This is expalined in grails docs(http://grails.github.io/grails-doc/latest/ref/Domain%20Classes/belongsTo.html).

Also, what is the difference between using following two :

Class Books{
    String name
    static belongsTo = [author : Author]
} 
Class Books{
    String name
    Author author
}

static belongsTo = [author : Author] is used only for cascading purposes, Is it true or does it have different use cases.

Can anyone explain these in detail without relating it to hasOne or hasMany. Thanks in advance.

Upvotes: 0

Views: 220

Answers (2)

Emmanuel Rosa
Emmanuel Rosa

Reputation: 9885

Using belongsTo without a back-reference is necessary for many-to-many associations. For example, lets assume you have the following domain classes:

class Book {
    String name
    Author author

    static hasMany = [categories: Category]
}

class Category {
    String name

    static hasMany = [books: Book]
}

If you try to use them as-is you'd get an exception like this:

No owner defined between domain classes [class Book] and [class Category] in a many-to-many relationship. Example: static belongsTo = Category

The solution is to make one of the domain classes the owner of the many-to-many association. Using my example, I think it makes more sense to make the Category the owner. However, a back-reference would not work because there could be multiple Categorys. So, this is where a belongsTo without a back-reference comes in:

class Book {
    String name
    Author author

    static hasMany = [categories: Category]
    static belongsTo = Category
}

Upvotes: 1

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27255

If you use static belongsTo = [author: Author] then a property named author of type Author is added to the class as a back reference. With static belongsTo = Author that does not happen.

Upvotes: 0

Related Questions