是否可以在 returns 自定义实体的 JPA 查询中添加 having 子句?
Is it possible to add a having clause in JPA query that returns custom entity?
我有以下 jpa 查询(我从中删除了不相关的信息):
@Query(value = "SELECT new SomeEntitySummary(et.id, count(ret.id)) " +
"FROM SomeEntity et left join SomeRelatedEntity ret on ( ... ) " +
"WHERE ... " +
"group by et.id"
)
它 returns 结果是一个自定义对象,而不是实体。
是否可以在其中包含一个 having 子句?
sql 等价物有效,看起来像:
select et.id,count(ret.id)
from someentity et
left join somerelatedentity ld on (...)
group by et.id
**having count(ret.id) between 1 and 100**
在jpa查询中可以这样写吗?我还没有设法找到任何相关的例子:(
是的,这是可能的。根据休眠文档(参见 15.51. Group by 部分)。
In a grouped query, the where clause applies to the non-aggregated values (essentially it determines whether rows will make it into the aggregation). The HAVING
clause also restricts results, but it operates on the aggregated values.
The HAVING
clause follows the same rules as the WHERE
clause and is also made up of predicates. HAVING
is applied after the groupings and aggregations have been done, while the WHERE
clause is applied before.
因此,您可以通过以下方式将 having 子句添加到您的第一个查询中:
SELECT new SomeEntitySummary(et.id, count(ret.id))
FROM SomeEntity et left join SomeRelatedEntity ret on ( ... )
WHERE ...
group by et.id
having count(ret.id) between 1 and 100
我有以下 jpa 查询(我从中删除了不相关的信息):
@Query(value = "SELECT new SomeEntitySummary(et.id, count(ret.id)) " +
"FROM SomeEntity et left join SomeRelatedEntity ret on ( ... ) " +
"WHERE ... " +
"group by et.id"
)
它 returns 结果是一个自定义对象,而不是实体。
是否可以在其中包含一个 having 子句?
sql 等价物有效,看起来像:
select et.id,count(ret.id)
from someentity et
left join somerelatedentity ld on (...)
group by et.id
**having count(ret.id) between 1 and 100**
在jpa查询中可以这样写吗?我还没有设法找到任何相关的例子:(
是的,这是可能的。根据休眠文档(参见 15.51. Group by 部分)。
In a grouped query, the where clause applies to the non-aggregated values (essentially it determines whether rows will make it into the aggregation). The
HAVING
clause also restricts results, but it operates on the aggregated values.The
HAVING
clause follows the same rules as theWHERE
clause and is also made up of predicates.HAVING
is applied after the groupings and aggregations have been done, while theWHERE
clause is applied before.
因此,您可以通过以下方式将 having 子句添加到您的第一个查询中:
SELECT new SomeEntitySummary(et.id, count(ret.id))
FROM SomeEntity et left join SomeRelatedEntity ret on ( ... )
WHERE ...
group by et.id
having count(ret.id) between 1 and 100