我可以肯定我做错了,因为这显然行得通。简化的类:
class Person {
String name
static hasMany = [cats:Cat]
}
class Cat {
String name
Person person
static belongsTo = Person
static constraints = {
person(nullable:false)
}
String toString() {
"${person.name}-${name}"
}
}
简单的东西,一个人有很多猫,猫必须只属于一个人。
现在,当我在Service类中执行以下操作时,会得到奇怪的结果:
delete(Cat cat) {
Person owner = cat.person
log.debug("Cats before removing ${cat} (id=${cat.id}): ${owner.cats} -- ${owner.cats*.id}")
owner.removeFromCats(cat);
log.debug("Removed from owner ${owner}, owner now has ${owner.cats} -- ${owner.cats*.id}")
log.debug("Cat to delete is now: ${cat} and belongs to... ${cat.person}")
cat.delete(flush:true)
}
错误是“对象将被保存,等等”
org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations)
当调用该方法删除“鲍勃”(Bob)拥有的猫“蓬松”时,奇怪的是调试结果:
Cats before removing Bob-Fluffy (id=1356): [Bob-Fluffy] -- [1356]
Removed from owner Bob, owner now has [null-Fluffy] -- [1356]
Cat to delete is now: null-Fluffy and belongs to... null
“removeFrom”实际上是不是从集合中删除了对象,这是怎么回事?我清理并重新编译。为什么我不能删除此对象,这几乎是一个茫然。
最佳答案
我会尝试将外地人删除为“人”人,而只留下这样的belongsTo场
class Cat {
String name
static belongsTo = [person:Person]
static constraints = {
person(nullable:false)
}
String toString() {
"${person.name}-${name}"
}
}
关于grails - grails 2.5.1 removeFrom一对多给出奇怪的行为(不删除),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39977793/