grails - 一个安装程序级联如何保存,更新和删除分别由一个共享域类组成的多个域类的操作?

标签 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
}

好多了...

最佳答案

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

static mapping = {
  enitityC cascade: 'all'
}

关于grails - 一个安装程序级联如何保存,更新和删除分别由一个共享域类组成的多个域类的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18539474/

相关文章:

oracle - 将Oracle和H2用于同一应用程序时Grails中的ID生成问题

grails - GORM hasMany使用多个列

spring - 在grails中发布升级spring插件

grails - 如何从GORM的子表中获取某些行

tomcat - 如何删除 grails 项目上的 war 和项目名称

hibernate - Grails钩入GORM beforeUpdate()

grails - 奇怪的插入后

java - Grails:检查分离的对象是否在附加的集合中

grails - 从类名称创建grails域类

grails - 在其父 View 中使用表单创建对象的正确方法?