grails 2.5.1 removeFrom 一对多给出奇怪的行为(不删除)

grails 2.5.1 removeFrom one-to-many giving strange behavior (not removing)

我很确定我做错了什么,因为这显然有效。简化 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}"
  }
}

简单的东西,一个人有很多只猫,猫一定只属于一个人。

现在,当我在服务 class 中执行以下操作时,我得到了奇怪的结果:

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)
}

错误是"object would be resaved, blah blah"

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" 实际上并没有从集合中删除对象?我清理并重新编译。几乎不知道为什么我不能删除这个对象。

我会尝试将字段 person 删除为 Person person 并只保留 belongsTo 字段,如下所示

class Cat {
  String name
  static belongsTo = [person:Person]
  static constraints = {
    person(nullable:false)
  }
  String toString() {
    "${person.name}-${name}"
  }
}

看起来在我的案例中发生的事情是 cat.person 不知何故变得陈旧,即使它是方法中的第一件事。调用cat.refresh()没用,从猫身上解压后调用owner.refresh()

我会这样更改域 class。

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}"
   }
}

服务中class

delete(Cat cat) {
  cat.delete(flush:true)
}

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

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