HQL 结合了“distinct”和“order by”

问题描述 投票:0回答:2

如果我删除“distinct”或“order by”,则此查询有效,但组合起来不起作用。我正在尝试效仿一些例子。你能解释一下吗?

String queryString = "select distinct event.county from Event as event order by event.county.county"

[main] - [ERROR] SqlExceptionHelper.logExceptions():144 >> ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
  Position: 215

生成的SQL

select distinct county1_.Id as Id4_, county1_.County as County4_ from Event event0_ inner join County county1_ on event0_.CountyID=county1_.Id cross join County county2_ where event0_.CountyID=county2_.Id order by county2_.County 
hibernate jpa jpa-2.0 hql
2个回答
7
投票

尝试使用

select distinct county from Event event
inner join event.county county
order by county.county

0
投票

发生这个错误的原因是 Hibernate 不会加载 SELECT 语句中嵌套对象的所有数据。它只会加载它们的 id,因此只有当您调用某个地方时才会检索它的数据。这是一种节省内存资源的策略,因为只有在实际需要时才会获取数据。

您可以通过将 JOIN 更改为 FETCH JOIN 来更改此行为。

SELECT DISTINCT county FROM Event event JOIN FETCH event.count county ORDER BY county.county

“获取”连接允许使用单个选择来初始化值的关联或集合及其父对象。

更多内容请点击以下链接

https://docs.jboss.org/hibernate/core/3.3/reference/en-US/html/queryhql.html#:~:text=A%20%22fetch%22%20join%20allows%20associations%20or %20collections%20of%20values%20to%20be%20initialized%20along%20with%20their%20parent%20objects%20using%20a%20single%20select.

© www.soinside.com 2019 - 2024. All rights reserved.