Grails GORM 上的一元关系

Uniary Relationship on Grails GORM

基于此 GORM 域 class:

class Component implements Serializable {
    Long id
    String name
    Double total
    Long parentComponentId

    static mapping = {
        ...
    }

    static constraints = {
        ...
        parentComponentId nullable: true
    }
}

我的问题是:

  1. 在这种情况下,我们如何将域 class 引用到自身 parentComponentIdComponent.
  2. 的另一个实例
  3. 如果解决了#1 中的引用问题,我该如何执行类似这样的查询:

    select a.*, b.* from COMPONENT a join COMPONENT b on a.id = b.parentComponentId group by a.id having sum(b.total) = a.total

第一个问题可以这样做。

class Component implements Serializable {
    Long id
    String name
    Double total
    static belongsTo = [parentComponentId:Component]
    static mapping = {
        ...
    }

    static constraints = {
        ...
        parentComponentId nullable: true
    }
}

只需将 Long parentComponentId 更改为 Component parentComponent。您也不需要 Long id 属性,因为 grails 会为您添加它:

class Component implements Serializable {
    String name
    Double total
    Component parentComponent

    static constraints = {
        parentComponent nullable: true
    }
}

那么就可以同时访问父组件和父组件id:

assert Component.read(1).parentComponentId == Component.read(1).parentComponent.id

如果你想进行级联删除,你需要删除 parentComponent 属性 并添加:

static hasMany = [nestedComponents: Component]
static belongsTo = [parentComponent: Component]

我假设你有 0:N 关系,如果没有,你需要改变它。检查 the documentation for defining associations.

关于你的第二个问题,遗憾的是你还不能在条件中使用 havinghttps://jira.grails.org/browse/GRAILS-7880

不过您可以使用 HQL 来完成:

Component.executeQuery("""
   select parent from Component parent, Component nested
   where nested.parentComponent = parent
   group by parent
   having parent.total = sum(nested.total)
""".toString())