Grails - 将多对多父/子关系映射到单个连接表

时间:2012-03-20 07:43:46

标签: hibernate grails groovy nhibernate-mapping gorm

我的问题基于以下(简化的)Grails域类

class Dimension {

    String name

    static hasMany = [
        children: Dimension,
        parents: Dimension
    ]
}

有没有办法将多对多父母/子女关系映射到一个联接表?

1 个答案:

答案 0 :(得分:7)

据我所知,唯一的方法是创建另一个代表父子关系的域类

class DimensionDependency {
  Dimension parent
  Dimension child

  static belongsTo = Dimension
}

class Dimension {
  static hasMany = [parentDependencies: DimensionDependency]
  static mappedBy = [parentDependencies: 'child']
  static mapping = { parentDependencies cascade: 'all-delete-orphan' }
}

mappedBy关键字指定引用DimensionDependency的对象始终是子对象。通过在映射中指定all-delete-orphan,我们确保从子项中删除parentDependency时,会从数据库中删除关联的DimensionDependency

您还可以在Dimension类中添加便捷方法,以封装DimensionDependencies上的操作,使界面更像GORM。

  static transients = ['children', 'parents']

  Set<Dimension> getChildren()
  {
    AssignmentDependency.findAllByParent(this).child
  }

  Set<Dimension> getParents()
  { 
    parentDependencies?.parent ?: []
  }

  Dimension addToParents(Dimension parent)
  {
    if (!parentDependencies.find { it.parent == parent && it.child == this })
    {
      addToParentDependencies(new DimensionDependency(parent: parent, child: this))
    }
    return this
  }

  Dimension removeFromParents(Dimension parent)
  {
    def dep = parentDependencies.find { it.parent == parent }
    removeFromParentDependencies(dep)
    dep.delete(flush: true)
    return this
  }

我已经使用这种方法一段时间了,到目前为止没有遇到任何麻烦。