`
rikugun
  • 浏览: 345668 次
  • 性别: Icon_minigender_1
  • 来自: 南宁
社区版块
存档分类
最新评论

GORM 笔记 One to One

阅读更多
例子中用Face 和 Nose作关系的例子
一对一有3种情况:
1.Nose作为Face的一个属性保存. 也就是说Nose 相当于 Face的一个内部类.

2.双向关联

3.级联关联
如果在Nose中设置的是
static belongsTo = Face

static belongsTo = [face:Face]

的区别是,前者是单向关联+级联,face可以通过
face.nose

获得Nose,而
nose.face

是没有的,后者有

原文:
引用

One-to-one
A one-to-one relationship is the simplest kind, and is defined trivially using a property of the type of another domain class. Consider this example:

Example A

class Face {
    Nose nose
}
class Nose {
}

In this case we have unidirectional one-to-one relationship from Face to Nose. To make this relationship bidirectional define the other side as follows:

Example B

class Face {
    Nose nose
}
class Nose {
Face face
}

This is bidirectional relationship. However, in this case no updates are cascading from either side of the relationship.

Consider this variation:

Example C

class Face {
    Nose nose
}
class Nose {
static belongsTo = [face:Face]
}

In this case we use the belongsTo setting to say that Nose "belongs to" Face. The result of this is that we can create a Face and save it and the database updates/inserts will be cascaded down to Nose:

new Face(nose:new Nose()).save()

The example above will save both face and nose. Note that the inverse is not true and will result in an error due to a transient Face:

new Nose(face:new Face()).save() // will cause an error

Another important implication of belongsTo is that if you delete a Face instance the Nose will be deleted too:

def f = Face.get(1)
f.delete() // both Face and Nose deleted

Without belongsTo deletes would not be cascading and you would get a foreign key constraint error unless you explicitly deleted the Nose:

// error here without belongsTo
def f = Face.get(1)
f.delete()

// no error as we explicitly delete both def f = Face.get(1) f.nose.delete() f.delete()

You could keep the previous relationship as unidirectional and allow saves/updates to cascade down by doing the following:

class Face {
    Nose nose
}
class Nose {
static belongsTo = Face
}

Note in this case because we are not using the map syntax in the belongsTo declaration and explicitly naming the association. Grails will assume it is unidirectional. The diagram below summarizes the 3 examples:


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics