如何为多个域类(由单个共享域类组成)设置级联保存,更新和删除操作?

时间:2013-08-30 18:38:09

标签: grails gorm grails-domain-class

给出以下域类:

共享实体(C)不能使用belongsTo为A和B设置级联,因为实例只会属于一个或另一个。

使用Gorm对此进行建模的最佳方法是什么?

class EntityA {
    static hasOne = [enitityC: SharedEntityC]
}

class EntityB {
    static hasOne = [enitityC: SharedEntityC]
}

class SharedEntityC {
   String foo
   // Can't use belongsTo to set up cascading
}

我看过以下内容:

http://grails.org/doc/2.0.x/guide/single.html#cascades
http://grails.org/doc/2.0.x/guide/single.html#customCascadeBehaviour


我尝试过策略模式:

interface Shareable {
    Shared sharedEntity
}
class EntityA implements Shareable {
    static hasOne = [sharedEntity: Shared]
}
abstract class Shared {
    static belongsTo = [shareable: Shareable]
}
class SharedEntityC extends Shared {
   String foo
}

但据一些人说,这是不合时宜的,而Gorm似乎只关心具体的课程。


我尝试过拦截器:

class EntityA {
    SharedEntityC enitityC

    def afterDelete {
        this.entityC.delete() // Results in readonly session error
    }
}

class EntityA {
    SharedEntityC enitityC

    def beforeDelete {
        this.entityC.delete() // Results in fk constraint violation
    }
}

另一种选择是:

class EntityASharedEntityC {
    EntityA entityA
    SharedEntityC entityC
    ...
    // a bunch of static methods for managing the relationship
    ...
}
class EntityBSharedEntityC {
    EntityB entityB
    SharedEntityC entityC
    ...
    // a bunch of static methods for managing the relationship
    ...
}

...
// Plus a new class for each entity containing SharedEntityC.
...

但这似乎在定义直接的复合关系方面还有很长的路要走。


在回答之前:

class EntityA {
    SharedEntityC enitityC

    def afterDelete() {
        this.deleteSharedEntityC()
    }

    void deleteSharedEntityC() {
        if(this.sharedEntityC) {
            this.sharedEntityC.beforeDelete() // It has some cleanup to do itself
            SharedEntityC.executeUpdate('delete SharedEntityC where id=:id', 
                          [id: this.sharedEntityC.id]) // Go around Gorm
        }
    }
}

即使我找到了一个可以忍受的解决方案,我想知道这些类是否可以以不需要我这样弯曲Gorm的方式建模。

欢迎并赞赏任何建议......: - )


答案之后:

class EntityA {
    SharedEntityC entityC

    static mapping = {
        entityC cascade: 'all'
    }
}

class EntityB {
    SharedEntityC entityC

    static mapping = {
        entityC cascade: 'all'
    }
}

class SharedEntityC {
   String foo
   // Leave out belongsTo
}

好多了......

1 个答案:

答案 0 :(得分:4)

在实体类中,您是否尝试指定级联:

static mapping = {
  enitityC cascade: 'all'
}