Grails的beforeDelete许多,许多关系(grails beforeDelete wit

2019-10-18 06:05发布

我有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与注册之间的关系被删除,当我打电话删除的是POI的beforeDelete,但是当它试图有效地执行删除,我有以下错误:

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

Answer 1:

在大多数情况下,GORM,有许多一对多的关系处理,而无需手动创建一个类来表示连接表创造了很多麻烦。

这方面的一个例子是Spring Security的核心插件的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
}


文章来源: grails beforeDelete with many-to many relation