Grails多对一级联删除麻烦

Grails many-to-one cascaded deletion trouble

给定以下域 类:

class Location {
    String city

    static belongsTo = [ author: Author ]
}
class Author {
    String name
    Location location
}

当我这样做时:

def l = new Location(city: "Boston")
l.save()

def a = new Author(name: "Niall Ferguson", location: l)
a.save()

我可以使用 a.delete() 删除我的作者,但是如果我尝试使用 l.delete() 删除我的位置,我会收到此错误消息:

org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations): [Location#17]

好的,让我从关联中删除要删除的对象,然后重试:

author.location = null // Assuming these two statements are the right way
location.author = null // to to this.

现在,当我再次尝试 l.delete() 时,我得到了这个:

ERROR util.JDBCExceptionReporter  - Referential integrity constraint violation: "FKAC2D218B9615BDBA: PUBLIC.AUTHOR FOREIGN KEY(LOCATION_ID) REFERENCES PUBLIC.LOCATION(ID) (18)";

那我做错了什么?在这种情况下,甚至可以删除位置并保留作者吗?

当我尝试重现您的代码时,我的第一个错误出现在 l.save() 中。在您的 class 中,您所在域 Location 中的字段作者是必需的。在您的示例中,您无法在没有作者的情况下保存位置。 您应该始终检查 save() 的 return 值或使用 failOnError: true 来发现这样的小错误。

话虽这么说,但在我看来,您正在模拟一对一的关系。不是多对一,否则一个 Location 怎么会有一个 Author? (我同意 grails 文档在这件事上有点混乱)

相反,我创建了以下 classes,假设作者有一个位置,但同一位置可以被许多作者引用。

class Author {
    String name
    Location location
}

class Location {
    String city
}

现在您违反了引用完整性约束,基本上,如果不先删除与该位置相关的所有作者,您就无法删除位置。

如果您希望删除级联起作用,我会使用像这样的双向一对多关系

class Author {
    String name
    static belongsTo = [location: Location]
}
class Location {
    String city
    static hasMany = [authors: Author]
}

关于你的最后一个问题,据我了解你的情况,你不能删除位置并保留作者。我假设许多作者都与同一地点有关。那么,如果您删除该位置,那么所有作者对该位置的引用应该如何处理?