我有 2 个具有多对多关系的域类。当我删除属于另一个的实体时,我必须先删除关系以避免外键错误。
我想将此代码放在 beforeDelete 事件中,但我遇到了 optimistc 锁定问题。这是域类的代码:
class POI {
static belongsTo = [Registration];
static hasMany = [registrations: Registration]
def beforeDelete = {
def poiId = this.id
POI.withNewSession { session ->
def regs = Registration.withCriteria{
pois{
idEq(this.id)
}
}
def poi = POI.get(poiId)
if(poi != null && regs.size() > 0){
regs.each{
it.removeFromPois(poi)
}
poi.save(flush: true)
}
}
}
}
}
class Registration {
static hasMany=[pois: POI];
}
所以 POI 和 Registration 之间的关系被删除了,在 beforeDelete 中,当我在 poi 上调用 delete 时,但是当它尝试有效地执行删除时,我有以下错误:
optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException:
Row was updated or deleted by another transaction (or unsaved-value mapping was
incorrect): [ambienticwebsite.POI#22]
任何人都知道如何通过使用 beforeDelete 来解决这个问题?