【问题标题】:Uniary Relationship on Grails GORMGrails GORM 上的一元关系
【发布时间】:2015-08-05 06:21:21
【问题描述】:

基于这个 GORM 域类:

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

    static mapping = {
        ...
    }

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

我的问题是:

  1. 在这种情况下,我们如何将域类引用到自身 parentComponentIdComponent 的另一个实例。
  2. 如果解决了 #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

【问题讨论】:

标签: grails grails-orm


【解决方案1】:

只需将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())

【讨论】:

    【解决方案2】:

    第一个问题你可以这样做。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-22
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      相关资源
      最近更新 更多