2010-10-09 99 views
0

我有以下的域刪除m比米還試圖級聯刪除一個-2-酮

class Committee { 
    String name 
    BoardCommitteeType boardCommitteeType 
    Date dateCreated 
    Date lastUpdated 
    User createdBy 
    User modifiedBy 

    static belongsTo = [ 
     board: Board, 
    ] 

    static hasMany = [   
     members: User 
    ] 
} 

class User { 

    static hasMany = [    
     committees: Committee,  
    ] 

    static belongsTo = [ 
     Board, Committee 
    ] 
} 

的問題是,當我嘗試做一個board.removeFromCommittees(委員會)我會得到以下例外:

刪除的對象將通過級聯重新保存(從關聯中刪除刪除的對象):[com.wbr.highbar.User#1];

我明白這意味着什麼。我不明白的是爲什麼我得到它。另一個有趣的地方是,如果我在委員會實例中使creatdBy和modifiedBy爲null,那麼刪除工作就好了。這就是爲什麼我認爲GORM正在嘗試級聯一對一。我的理論是,這與用戶屬於委員會的事實有關。但我不知道如何解決這個問題。

+0

這種方法充滿了循環依賴關係,這就是導致問題的原因。考慮你是否可以重構你的領域模型。 – mfloryan 2010-10-09 19:04:27

+0

對於循環依賴是如何導致我的問題的,你能更具體一些嗎? – Gregg 2010-10-09 19:30:13

回答

0

級聯刪除受到域類之間belongsTo關係的影響。

由於Committee belongsTo Board,董事會被刪除時,刪除級聯到委員會。由於User belongsTo Committee,當委員會被刪除時,刪除級聯到用戶。

解決您的問題是刪除User belongsTo Committee關係。

註上你的域模型作爲一個整體:

你有很多很多一對多的關係。他們不一定是錯的,但他們可能是過於複雜的事情。你可能只是在使用時逃脫:

class Committee { 
    static hasMany = [boards: Board, users: User] 
} 

class Board { 
    static hasMany = [users: User] 
    static belongsTo = Committee // this is the only belongsTo you need, since if a 
           // committee is dissolved, presumably the board 
           // will be dissolved as well (unless you have 
           // cross-committee boards) 
} 

class User { 
    // doesn't define any relationships, 
    // let the Committee/Board domains handle everything 

    // also, this is presuming that users are at a higher level than committees, i.e. 
    // a user could belong to multiple committees 
} 
+0

如果我刪除用戶belongsTo委員會,Grails抱怨說我對M2M關係沒有自己的一面。所以這並不能解決我的問題。我所做的解決這個問題的方法是我已經完全刪除了M2M,並編寫了一個具有user.id和committee.id的組合ID的CommitteeMembers類。對我來說,這是GORM如何實現M2M的限制,因爲很少有「擁有」的一面。 – Gregg 2010-10-10 22:18:19

+0

但是我非常感謝幫助。 – Gregg 2010-10-10 22:19:21

+0

GORM和M2M的關係總是有點挑剔,我和你一直處於類似的情況。您是否嘗試了一個替代域模型的建議?這將刪除M2M並且不要求您手動編寫關係域。 – 2010-10-11 03:07:13