我很确定我做错了什么,因为这显然有效。 简化课程:
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”实际上并没有从集合中移除对象? 我清理并重新编译。 对于为什么我不能删除这个对象,我几乎不知所措。
I'm pretty much certain I'm doing something wrong since this obviously works. Simplified classes:
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}" } }Simple stuff, a person has many cats, cats must belong to only a single person.
Now when I do the following in a Service class, I get strange results:
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) }And the error is "object would be resaved, blah blah"
org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations)The weird bit is the debug results, when called to remove cat "Fluffy" who's owned by "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... nullWhat's going on that "removeFrom" isn't actually removing the object from the collection? I cleaned and recompiled. Pretty much at a loss as to why I can't delete this object.
最满意答案
我会尝试将字段人员删除为人员,并仅保留像这样的belongsTo字段
class Cat { String name static belongsTo = [person:Person] static constraints = { person(nullable:false) } String toString() { "${person.name}-${name}" } }It looks like what was happening in my case is that cat.person has getting stale somehow, even though it's the first thing in the method. Calling cat.refresh() didn't work, but calling owner.refresh() after extracting it from the cat.
更多推荐
发布评论