hibernate - 在 GORM 中查询关联的子查询

标签 hibernate grails subquery grails-orm

我在 GORM 中有以下域。

class Topic {
static hasMany = [resources: Resource, subscriptions: Subscription]
}

class Resource {
static belongsTo = [resourceOf: Topic]
}

class Subscription {
 static belongsTo = [subscriptionOf: Topic]
}

我一直无法找到使用标准/命名子查询运行子查询的语法。例如,我如何使用标准在 GORM 中编写以下查询。
select topic.id, 
(select count(*) from Resource where resourceOf.id = topic.id) as numRes,
(select count(*) from Subscription where subscriptionOf.id = topic.id) as numSubs
from topic
where topic.id in (<My topic ids>)
group by topic.id;

这是非常基本的事情,但我无法找到相同的文档。

有谁知道如何在 GORM 中使用 namedQueries 来做到这一点?

我的 grails 版本是 2.4.4

最佳答案

您面临的问题是 namedQueries不应与预测(摘要)一起使用。退后一步,重新设置您对能做的和 的期望应该使用时完成 namedQueries .

命名查询是创建标识较大集合子集的查询的一种便捷方式。将其视为逐步过滤数据。如果您查看文档中的示例,您将看到正在演示的内容。这使得 namedQueries非常强大,但在那个特定的用例中。

来自 documentation 的示例:

// get all old publications with more than 350 pages
// and the word 'Grails' in the title
def pubs = Publication.oldPublicationsLargerThan(350).findAllByTitleLike('%Grails%')

另一个例子可能是:
def divisions = Division.locatedIn('Sweden').havingNoOustandingBalance().havingMoreThanXEmployees(50).currentlyOpen().notOnFire()

在其他用例中,例如处理摘要和预测,它们会达不到要求。不是因为它们设计不当或无能,而是因为这不是它们的设计初衷。

确实应该通过 createCriteria 创建预测和摘要或 HQL本身。

虽然你可以破解 namedQueries做预测和总结,你会和框架做斗争。使用正确的工具完成正确的工作,并完成更多工作。

更新
然而,所有这一切都说,这个blog post解释了如何使用具有命名查询(和条件)的投影。它应该让您更好地了解 GORM 中的投影如何工作。

关于hibernate - 在 GORM 中查询关联的子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28765058/

相关文章:

hibernate - Hibernate 中的多图

java - JPA 父子中具有复合 id 的一对多关系

java - Hibernate 与 SparkJava 不兼容?

database - 如何使用 Liquibase 删除 Grails 中的索引

mysql - 在 MYSQL 查询中使用 If

java - 包 org.hibernate 可以从多个模块访问 : hibernate. commons.annotations, hibernate.core

MySQL INSERT INTO 带外键的表速度很慢

mysql - 复杂的mySQL 两表查询

Mysql全选时通过FK获取实际值

grails - GRAILS以to_char命名查询