I tried to define one to one relation in 2 different way:
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 mapping. Unfortunately DB has different structure in both cases.
Case 1:
Case 2:
Why once Car and once Engine keeps link to second table.
Where is my problem? When I am looking at the code, from DDD perspective, both cases suggest that Car class is more important and Car aggregates Engine. Unfortunately when I look from DB side on case 2 I would rather said that it is opposite - Engine aggregate Car. Of course I can use first approach, but most of publication I saw about grails, present second way for defining relation. Maybe I misunderstood something and I use hasOne in wrong way?
The documentation on hasOne
states that using this creates a bi-directional one-to-one relationship where the foreign key is on the child.
The belongsTo
means that actions performed on the parent (eg save and update) will be cascaded by hibernate to 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
then use Engine engine
on Car
.
In both cases use belongsTo = [car: Car]
on Engine
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With