Grails - Trying to remove objects, but they come b

2019-08-27 20:37发布

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?

标签: grails gorm
1条回答
Evening l夕情丶
2楼-- · 2019-08-27 21:25

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.

查看更多
登录 后发表回答