1

我有 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 来解决这个问题?

4

1 回答 1

4

在使用 GORM 的大多数情况下,处理多对多关系而不手动创建表示连接表的类会带来很多麻烦。

这方面的一个例子是Spring Security Core Plugin 的 PersonAuthority 类

一个多对多的例子,删除任一端也会删除连接条目:

class POI {
    def beforeDelete() {
        RegistrationPOI.withNewSession {
            def rps = RegistrationPOI.findByPOI(this)
            rps.each { it.delete(flush: true) } // flush is necessary
        }
    }

    /* example convenience method to get directly
     * from a POI to the associated Registrations */
    Collection<Registration> getRegistrations() {
        RegistrationPOI.findByPOI(this)
    }
}

class Registration {
    def beforeDelete() {
        RegistrationPOI.withNewSession {
            def rps = RegistrationPOI.findByRegistration(this)
            rps.each { it.delete(flush: true) } // flush is necessary
        }
    }
}

class RegistrationPOI {
    Registration registration
    POI poi
}
于 2013-06-07T15:09:54.170 回答