gpt4 book ai didi

hibernate - Grails:级联删除和外键

转载 作者:行者123 更新时间:2023-12-02 15:15:06 24 4
gpt4 key购买 nike

public class Room {
static belongsTo = [hotel:Hotel]
Source source
long sourceid
RoomType type
float price
float oldPrice
Currency currency
boolean isShown = false
boolean approved = false
static hasMany = [roomTexts:RoomText]

def beforeDelete () {
Photos.withNewSession {
Photos.findAllByRoom(this).each {photosInstance->
photosInstance.delete()
}
}

RoomFeatures.withNewSession {
RoomFeatures.findAllByRoom(this).each {roomF->
roomF.delete()
}
}
}

}


然后:
def room = Room.get(1) 
room.delete()

将抛出com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException。
Cannot delete or update a parent row: a foreign key constraint fails (`prod_test`.`photos`, CONSTRAINT `FKC50C8881EC5F6358` FOREIGN KEY (`room_id`) REFERENCES `room` (`id`))

发生这种情况是因为照片删除 session 尚未刷新到数据库,并且Hibernate尝试删除Room实体,我认为...

这是房间删除代码:
Room.withTransaction{status->
roomInstance.delete(flush: true)
}

是否有任何解决方法或“正确方法”来解决此问题?
当然,我可以在删除房间之前手动删除所有照片,但是使用beforeDelete有助于保持代码干净并避免代码重复。

最佳答案

为什么不能将hasMany列表中的照片与RoomText一起保存,而使照片属于Room?

关于hibernate - Grails:级联删除和外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3469051/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com