Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails one to one relation

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: enter image description here

Case 2: enter image description here

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?

like image 353
mrok Avatar asked Jul 20 '12 00:07

mrok


1 Answers

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

like image 53
David Genn Avatar answered Nov 15 '22 21:11

David Genn