共享实体(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
}
好多了......
答案 0 :(得分:4)
在实体类中,您是否尝试指定级联:
static mapping = {
enitityC cascade: 'all'
}