【问题标题】:Gorm not doing joinGorm 没有加入
【发布时间】:2012-11-15 21:32:25
【问题描述】:

我正在尝试构建我称为组的类的层次结构。域名相当简单:

class SubGroup implements Serializable {
    Group child
    Group parent

    static mapping = {
        id composite: ['child', 'parent']
    }
}

class Group implements Serializable {           
    int groupId
    String key
    String title

    static mapping = {
        id name: 'groupId'
    }
}

基本上,我想建立一个团体父母及其相关子女的地图。所以我遍历每条记录(如果有更简洁的方式来查询地图,我很高兴听到它)并为它创建地图条目。

Map hierarchy = [:]
SubGroup.list().each { relation ->
    if (!hierarchy[relation.parent]) {
        hierarchy[relation.parent] = new HashSet()
    }

    hierarchy[relation.parent] << relation.child
}

我认为hibernate会使用一些简单的查询来做这样的事情:

select * from sub_group s, group c, group p 
where s.child_id = c.group_id and s.parent_id = p.group_id

但它没有进行连接。它正在对子组进行查询,然后对组表进行 n 次查询(N+1 选择问题)。啊。我听说在 2.0 中休眠 query cache 有问题,所以我禁用了它。我尝试将 lazy: falsefetch: join 添加到我的 SubGroup 域类中,用于父列和子列,但没有成功。我尝试将 (fetch: [child: 'eager']) 作为参数添加到 list 方法。它不会进行连接。我错过了什么吗?老实说,它甚至不需要进行连接,因为我只访问 groupId 外键属性,尽管稍后我将需要 key 和 title 属性。

当然,我可以将子属性和父属性设置为整数,并在需要其余数据时自己进行查询,或者我可以使用 HQL 和其他一些方法将其限制为单个查询,但似乎像 GORM 应该为我做这件事。感谢您的帮助。
问候,

吉姆

【问题讨论】:

  • 我想你对hibernate(GORM下的层)持久化框架是如何工作的有点不了解。我建议你在开始使用 grails/gorm 之前先阅读一些关于 Hibernate 的好书。
  • 嗯,我承认我是 Grails 甚至是 hibernate 的新手,但你可以尝试为我的问题提供解决方案,而不是屈尊地暗示 hibernate 不是什么。

标签: grails grails-orm


【解决方案1】:

似乎我可以在不为每个孩子和父母进行选择调用的情况下让它工作的唯一方法是改为执行 HQL 查询,而不是使用如下所示的列表方法:

Map hierarchy = [:]
def subGroups = SubGroup.executeQuery("SELECT s.parent, s.child FROM SubGroup s")
subGroups.each { relation ->
    if (!hierarchy[relation[0]]) {
        hierarchy[relation[0]] = new HashSet()
    }

    hierarchy[relation[0]] << relation[1]
}

因此,我实际上只使用 SubGroup 域类来定义关系。我想我应该能够通过某种映射来做到这一点,但我不知道怎么做。

【讨论】:

    猜你喜欢
    • 2013-11-13
    • 2012-01-13
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    相关资源
    最近更新 更多