【问题标题】:Write criteria to mimic join query grails编写条件来模拟连接查询 Grails
【发布时间】:2014-06-24 09:49:29
【问题描述】:

我正在使用 grails 2.2.4 并想编写可能生成 SQL 的标准:

select r.value from group g, rating r where r.groupId = g.id and g.name = ?

如果我们具有以下域结构:

class Group {
    String name
}

class Rating {
    Long groupId
    int value
}

如何使用 grails 标准编写此内容?

我写的是这样的:

def result = Rating.withCriteria {
    projections {
        property("value")
    }
    eq "groupId", new DetachedCriteria(Group).build {
        projections {
            property("id")
        }
        eq("name", "Group A")
    }
}

但是由此,hibernate 正在生成子查询。有什么猜测吗?

【问题讨论】:

  • 是否有理由将其建模为 id 的 Long 属性而不是普通的多对一关联 (Group group)?它将提供相同的表结构,但您可以以正常方式查询关联。

标签: grails


【解决方案1】:

您可能应该将域结构更改为面向对象。为此使用关联:[http://grails.org/doc/2.2.4/guide/GORM.html#gormAssociation]

您的代码将如下所示:

class Group {
    String name
}

class Rating {
    Group group
    int value
}

您的条件查询可能与此类似:

Rating.withCriteria {
    createAlias('group', '_group')
    eq('_group.name', 'Group A')
    projections {
        property('value')
    }
}

【讨论】:

    猜你喜欢
    • 2021-05-22
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    相关资源
    最近更新 更多