Grails - 试图删除对象,但它们会回来

时间:2013-07-01 19:14:58

标签: grails gorm

我有两个域类,Job和Description,简单的一对多关系:

Job.groovy

class Job {
    static hasMany = [descriptions: Description]

    static mapping = {
        descriptions lazy: false
    }
}

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请求时打印的内容:

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

为什么说明会在removeDescriptionFromJob操作中被移除,只是在show动作中立即返回?

1 个答案:

答案 0 :(得分:3)

removeFromDescriptions确实删除了jobInstancedescription的关系,但实体description仍然存在。

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

由于关系不存在,

不会导致o / p。代替上面的行尝试直接获取描述对象:

System.out.println("after remove: " + Description.get(//id you just disassociated))

您将成功获得说明。

为避免这种情况,您需要将以下映射属性添加到Job,以便在实体与父级分离后删除所有孤立。

descriptions cascade: "all-delete-orphan"

像:

class Job {
    static hasMany = [descriptions: Description]

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

GORM Bible - 必读。