Grails - Trying to remove objects, but they come back

家住魔仙堡 提交于 2019-12-12 01:06:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!