I have two domain classes, Job and Description, in a simple one to many relationship:
Job.groovy
class Job {
static hasMany = [descriptions: Description]
static mapping = {
descriptions lazy: false
}
}
Description.groovy
class Description {
static belongsTo = [job: Job]
}
I have two controller actions:
def removeDescriptionFromJob(Long id) {
def jobInstance = Job.get(id)
System.out.println("before remove: " + jobInstance.descriptions.toString())
def description = jobInstance.descriptions.find { true }
jobInstance.removeFromDescriptions(description)
jobInstance.save(flush: true)
System.out.println("after remove: " + jobInstance.descriptions.toString())
redirect(action: "show", id: id)
}
def show(Long id) {
def jobInstance = Job.get(id)
System.out.println("in show: " + jobInstance.descriptions.toString())
}
This is what gets printed when I submit a request to removeDescriptionFromJob:
before remove: [myapp.Description : 1]
after remove: []
in show: [myapp.Description : 1]
Why does the Description get removed in the removeDescriptionFromJob action, only to come back immediately afterwards in the show action?
removeFromDescriptions
did remove the relationship ofjobInstance
fromdescription
, but the entitydescription
still exists.System.out.println("after remove: " + jobInstance.descriptions.toString())
would result no o/p since the relation is non-existing. In place of the above line try to get the description object directly like:
You would get the description successfully.
To avoid that, you need to add the below mapping property to
Job
to remove all the orphans once an entity is detached from parent.descriptions cascade: "all-delete-orphan"
Like:
GORM Bible - A must-read.