给定以下域类:
共享实体(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/