1

给定以下域类:

共享实体 (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
}

好多了,好多了……

4

1 回答 1

4

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

static mapping = {
  enitityC cascade: 'all'
}
于 2013-08-31T03:43:37.097 回答