grails beforeDelete与多对多的关系

时间:2013-06-07 14:15:26

标签: grails many-to-many gorm cascading-deletes

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

1 个答案:

答案 0 :(得分:3)

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

这方面的一个例子是Spring Security Core Plugin's PersonAuthority class

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

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
}