Grails: Cascade delete and Foreign Keys
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()
}
}
}
}
Then:
开发者_如何学运维def room = Room.get(1)
room.delete()
Will throw 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`))
It happens because photos deletion session are not yet flushed into DB and Hibernate tries to delete Room entity, i think...
Here is room deletion code:
Room.withTransaction{status->
roomInstance.delete(flush: true)
}
Is there any workaround or "right way" to resolve this problem ?
Of course i could manually delete all photos before deleting room but using beforeDelete helps to keep code clean and avoid code duplication.Why can't you have photos in the hasMany list along with RoomText, and make photos belong to Room?
If the Photos are owned by the Room, you shouldn't have to delete them beforehand. Just delete the Room and the Photos go with it right? Although I'm not seeing the relationship between Photo and Room defined at all, maybe it would be clearer if you posted your Photo class.
精彩评论