One-to-One Relationships

I tried to define one-to-one relationships in two different ways:
Grails 2.0.3

Case 1:

class Car { String model Engine eng static constraints = { eng unique: true } } class Engine { Double capacity static belongsTo = [car : Car] } 

Case 2:

 class Car { String model static hasOne = [eng : Engine] static constraints = { eng unique: true } } class Engine { Double capacity static belongsTo = [car : Car] } 

looks similar, and both provide one-to-one bidirectional matching. Unfortunately, DB has a different structure in both cases.

Case 1: enter image description here

Case 2: enter image description here

Why once the car and once the Engine is associated with the second table.

Where is my problem? When I look at the code in terms of DDD, both cases indicate that the Car class is more important, and the Car aggregates Engine. Unfortunately, when I look at the case 2 from the side of the database, I would rather say that it is the other way around - the engine is an aggregate car. Of course, I can use the first approach, but most of the publication I saw about the grail, presenting the second way to determine the relationship. Maybe I misunderstood something and am using hasOne incorrectly?

+8
database grails gorm
source share
2 answers

The hasOne claims that this creates a bi-directional, one-to-one relationship in which the foreign key is on the child.

belongsTo means that actions performed on the parent (for example, saving and updating) will be cascaded by sleep mode for the child.

So, if you want the foreign key to be on Engine , use static hasOne = [engine:Engine] on Car .

If you want the foreign key to be on Car , use the Engine engine on Car .

In both cases, use belongsTo = [car: Car] on the Engine

+13
source share

I think you should try to do this.

  class Car { String model Engine engine static constraints = { eng unique: true } } class Engine { Double capacity Car car } 

I think it will work. You can read it here:

By default, the address association will map to the foreign key column address address_id.

http://grails.org/doc/latest/guide/GORM.html

in many-to-one / one-to-one comparisons


Hope this helps :)

-one
source share

All Articles