简体   繁体   中英

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: 在此处输入图片说明

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

I think you should try to make this aproach.

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


   class Engine {
       Double capacity
       Car car
   }

I think that will make it. You can read it here:

By default the address association would map to a foreign key column called address_id.

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

on the Many-to-One/One-to-One Mappings


Hope it helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM