![](/img/trans.png)
[英]Using Grails Transaction when saving two different domain object in one shot
[英]Grails one to one on two domain object
我想將一個孩子添加到兩個不同的父類中,如下所示:
第一:
class Member {
Profile profile
Member() {
this.profile = new Profile()
}
static mapping = {
profile cascade: 'all-delete-orphan'
}
}
第二:
class Team {
Profile profile
Team() {
this.profile = new Profile()
}
static mapping = {
profile cascade: 'all-delete-orphan'
}
}
孩子就是這樣定義的
class Profile() {
}
問題是當我保存父母時,它不保存孩子:
Member member = new Member().save(flush: true, failOnError: true)
assert !member.hasErrors()
assert member.profile
assert !member.profile.hasErrors()
assert member.profile.id //FAIL
我做錯了什么? 有更好的方法嗎?
更新:
我找到了這個
這種行為似乎需要“屬於”。 但是,為什么“級聯:'全部刪除-孤兒'”不強制這樣做呢? 因為在那種情況下我不能使用“屬於”
我復制了您的示例(稍作修改即可將組表名稱更改為非保留字),並且使用grails 2.2.1可以使級聯正常工作。 Member
和Group
其保存級聯到新創建的Profiles
。
假設您的類比這更復雜,則您在類中的其他地方可能會有錯誤(例如,在constraints
描述的級聯行為,而不是mapping
等)。
我找到了一個不錯的解決方案。 最好是在孩子中定義兩個父對象,但都可以為空。 像那樣:
class Profile() {
static belongsTo = [member: Member, team: Team]
static constraints = {
member nullable: true
team nullable: true
}
}
這樣,級聯行為就可以了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.