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`))
這是因爲照片刪除會話尚未刷新到DB和Hibernate試圖刪除房單位,我想......
這裏是房間刪除代碼:
Room.withTransaction{status->
roomInstance.delete(flush: true)
}
有沒有解決此問題的解決方法或「正確方法」?
當然,我可以在刪除房間之前手動刪除所有照片,但使用beforeDelete有助於保持代碼清潔並避免代碼重複。