Grails-尝试删除对象,但它们又回来了 [英] Grails - Trying to remove objects, but they come back

查看:79
本文介绍了Grails-尝试删除对象,但它们又回来了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个域类,即Job和Description,它们之间具有简单的一对多关系:

I have two domain classes, Job and Description, in a simple one to many relationship:

Job.groovy

Job.groovy

class Job {
    static hasMany = [descriptions: Description]

    static mapping = {
        descriptions lazy: false
    }
}

Description.groovy

Description.groovy

class Description {
    static belongsTo = [job: Job]
}

我有两个控制器动作:

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())
}

这是我提交removeDescriptionFromJob请求时打印的内容:

This is what gets printed when I submit a request to removeDescriptionFromJob:

before remove: [myapp.Description : 1]
after remove: []
in show: [myapp.Description : 1]

为什么在removeDescriptionFromJob操作中删除说明,而随后又在show操作中立即返回?

Why does the Description get removed in the removeDescriptionFromJob action, only to come back immediately afterwards in the show action?

推荐答案

removeFromDescriptions确实从description中删除了jobInstance的关系,但是实体description​​仍然存在.

removeFromDescriptions did remove the relationship of jobInstance from description, but the entity description still exists.

System.out.println("after remove: " + jobInstance.descriptions.toString())

由于该关系不存在,因此不会产生o/p.代替上一行,尝试直接获取描述对象,例如:

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))

您将成功获得说明.

为避免这种情况,一旦实体与父级分离,您需要将以下映射属性添加到Job以删除所有孤儿.

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"

赞:

class Job {
    static hasMany = [descriptions: Description]

    static mapping = {
        descriptions lazy: false, cascade: "all-delete-orphan"
    }
}

GORM圣经-必读

这篇关于Grails-尝试删除对象,但它们又回来了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆