一对一关联关系开发中用的没有一对多那么广泛,但是我觉得掌握以下还是有必要的,一对一关联关系有一张表存在外键,引用的一般是主表的主键。grails也对一对一关联关系提供了很好的支持,配置也是简单的不得了。grails配置一对一可以有下面三种选择:
class Face {
Nose nose
}
class Nose {
}这种属于单向关联,下面的这种则是双向关联,但是不能级联更新
class Face {
Nose nose
}
class Nose {
Face face
}class Face {
Nose nose
}
class Nose {
static belongsTo = [face:Face]
}class Face {
Nose nose
}
class Nose {
static belongsTo = Face
}1.创建领域对象
class PersonInfo {
Integer id;
String name;
CardInfo card;
static mapping = {
table ‘m_person‘
card column: ‘cardId‘
}
}
class CardInfo {
Integer id;
String birthday;
static belongsTo = [person:PersonInfo]
static mapping = {
table ‘m_card‘
}
}
2.通过控制器级联保存person和card
@Transactional
def savePersonAndCard(){
def p=new PersonInfo()
p.setName("caiyil")
def c=new CardInfo()
c.setBirthday("2008-01-03")
p.setCard(c)
p.save()
render "数据保存成功"
} //通过person查询birthday
def queryPersonBirthday(){
def personId=params.id
def p=PersonInfo.get(personId)
render p.getCard().getBirthday()
}
原文:http://blog.csdn.net/walkcode/article/details/24876921