0

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...  null

What'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.

4

3 回答 3

0

看起来在我的情况下发生的事情以cat.person某种方式变得陈旧,即使这是该方法中的第一件事。调用cat.refresh()不起作用,但owner.refresh()在从猫中提取后调用。

于 2016-10-11T14:35:12.317 回答
0

我会尝试将字段 person 删除为 Person person 并只留下像这样的 belongsTo 字段

class Cat {
  String name
  static belongsTo = [person:Person]
  static constraints = {
    person(nullable:false)
  }
  String toString() {
    "${person.name}-${name}"
  }
}
于 2016-10-11T13:19:50.417 回答
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)
}

进行域更改后,请从新数据库开始,因为架构会更改。

我认为这应该可以解决您的问题。

于 2016-10-11T15:10:55.987 回答