我非常肯定我做错了,因为这显然有效。简化课程:
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)
}
错误是"对象将被重新保存,等等等等#34;
org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations)
奇怪的是调试结果,当被调用以移除cat" Fluffy"谁拥有" 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"实际上是不是从集合中删除了对象?我清理并重新编译。几乎不知道为什么我不能删除这个对象。
答案 0 :(得分:0)
我会尝试将字段人员删除为Person person,并仅保留belongsTo字段,如此
class Cat {
String name
static belongsTo = [person:Person]
static constraints = {
person(nullable:false)
}
String toString() {
"${person.name}-${name}"
}
}
答案 1 :(得分:0)
看起来在我的情况下发生的事情是cat.person
以某种方式变得陈旧,即使这是方法中的第一件事。调用cat.refresh()
不起作用,但在从猫中提取后调用owner.refresh()
。
答案 2 :(得分:0)
我会改变域类。
class Person {
String name
static hasMany = [cats:Cat]
}
class Cat {
String name
Person person
// no need to add belongs to property here. it creates a join table that you may not need
static constraints = {
person(nullable:false)
}
String toString() {
"${person.name}-${name}"
}
}
在服务类
中delete(Cat cat) {
cat.delete(flush:true)
}
进行域更改后,请从新数据库开始,因为架构将更改。
我认为这应该可以解决你的问题。