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.