hibernate - grails/GORM/hibernate -hasMany map 未在父级的save()上同步

标签 hibernate grails groovy associations gorm

删除关联的实体并将此更改保留到数据库时出现问题。

有一个groovy对象的父对象,该对象具有许多与之关联的子实体。当我们找到此域对象并将此列表设置为null时,请调用parent.save(flush:true)
子元素保留在数据库中。希望这些已被删除。任何建议都很好。

class Parent {

static hasMany = [child:Child] ... }


和 child :
class Child {

belongsTo = [Parent] ... }


我们添加元素并删除:
def child = new Child()

def parent = new Parent(child:child)

parent.save(flush:true) def id = parent.id //from saved entity

/// in separate transaction

parent = Parent.get(id) //id from above parent.child = null

parent.save(flush:true)

// check database - child reference still there - expect to have been deleted


关于我们做错了什么的任何建议将不胜感激。使用Grails 1.3.5(最新版本)。

最佳答案

首先,您应该使用child.delete(flush:true)而不是分配null。只是不合适。 (对不起以前的错误)

我建议您阅读Peter Ledbrook系列:http://blog.springsource.com/2010/07/02/gorm-gotchas-part-2/。在您的情况下,搜索“删除 child ”

更新:如果您仍然没有阅读以上文章(特别有用):

要删除子级,首先需要将其从父级集合中删除,然后再将其删除。但是,这将导致属性不为null异常,因为您使用belongsTo关系。

解决方案:您可以将其添加到Parent类中:

static mapping = {
 childs cascade: "all-delete-orphan"
}

上面的映射将帮助删除所有没有 parent 的 child 。那你可以用
parent.childs.clear()

关于hibernate - grails/GORM/hibernate -hasMany map 未在父级的save()上同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4317508/

相关文章:

java - 错误如下所述

java - 配置hibernate暂时使用 "show-sql=false"

Grails无法解析插件

grails - 强制 Grails 使用带有正确语言代码的 message.properties?

grails - 从 2 个(或更多) Controller 中排除 Grails 过滤器

java - 好极了。按嵌套映射的键对映射数组进行排序

hibernate - org.hibernate.exception.GenericJDBCException : could not get next sequence value

hibernate - 有没有办法基于唯一键而不是主键(在 Hibernate 中)合并 JPA 实体?

gradle - 如何从另一个自定义插件应用 Kotlin jvm 插件?

java - 点语言标识符的正则表达式