Lets say I have a domain class named Tag in my Grails application.
class Tag {
String name // line number 1
User user // Line number 2
static constraints = {
}
static belongsTo = [User, Post]
}
I’m creating a relationship between User and Tag with the help of belongsTo keyword. But I have a doubt on line number 2, which is User user. Now placing this code in my Tag class affect the relationship between Tag and User in any way or it is only matter what we provide in belongsTo keyword?
And there are any tools to visualize the relationship between any classes in Grails application?
belongsTowith several classes is often suspect, as it means that instances will be in a composition relationships with several other domain objects. In my experience, it’s only useful if you know one will always benullwhen the other is set (but still, you may prefer to haveTagUserandTagPostderive aTagclass instead). I would suggest you remove one of thebelongsTo(probably Post).In your
PostandUserclasses you probably have ahasManyrelationship. It’s enough to create the relationship and don’t have to addbelongsToinTag. The only advantage of usingbelongsTois that updating or deleting aUserorPostwill cascade and saveTagsas well.If your use case for Tag is the conventional one (like tags on stackoverflow), you are trying to create many-to-many relationships (one user has many tags and one tag has many users. Same for post). You may use belongsTo in a many-to-many relationship to indicate who owns the relation. Read the documentation on many-to-many to understand how such relationships work.
Regarding your last question, IntelliJ has an integrated Domain classes dependencies visualization feature.