问题
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?
回答1:
removeFromDescriptions
did remove the relationship of jobInstance
from description
, but the entity description
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:
System.out.println("after remove: " + Description.get(//id you just disassociated))
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:
class Job {
static hasMany = [descriptions: Description]
static mapping = {
descriptions lazy: false, cascade: "all-delete-orphan"
}
}
GORM Bible - A must-read.
来源:https://stackoverflow.com/questions/17411981/grails-trying-to-remove-objects-but-they-come-back