Anonymous Human
Anonymous Human

Reputation: 1948

Grails relationship reference despite having a belongsTo

Let's say an Owned domain class belongs to an Owner domain class by having this declaration in its body:

static belongsTo [ Owner ]

Why then in some cases do I still see the Owned domain class also having a property or field like reference to the Owner domain class like

Owner owner

despite having the belongsTo clause in its body? Wouldn't the belongsTo declaration take care of the needed reference in this case?

Upvotes: 0

Views: 72

Answers (1)

Burt Beckwith
Burt Beckwith

Reputation: 75671

The combination of

static belongsTo = [ Owner ]

and

Owner owner

is essentially the same as

static belongsTo = [owner: Owner ]

because using the map form triggers (via an AST transformation) the creation of a property of type Owner with name owner.

My preference is to use the single statement however because it's the standard way to declare a bidirectional one-many and the other way feels like a side effect.

One reason that using the simpler form of belongsTo and declaring the owner property is when you have multiple parent domain classes, but some are bidirectional and some aren't, e.g.

static belongsTo = [Owner, OtherClass]
Owner owner

This way you make Owner/Owned bidirectional, but leave the OtherClass relationship unidirectional.

Upvotes: 2

Related Questions