0

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

Job.groovy

class Job {
    static hasMany = [descriptions: Description]

    static mapping = {
        descriptions lazy: false
    }
}

说明.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 操作中立即返回?

4

1 回答 1

3

removeFromDescriptions确实删除了jobInstancefrom的关系description,但实体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 圣经- 必读。

于 2013-07-01T19:43:58.733 回答