如果我删除“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
尝试使用
select distinct county from Event event
inner join event.county county
order by county.county
发生这个错误的原因是 Hibernate 不会加载 SELECT 语句中嵌套对象的所有数据。它只会加载它们的 id,因此只有当您调用某个地方时才会检索它的数据。这是一种节省内存资源的策略,因为只有在实际需要时才会获取数据。
您可以通过将 JOIN 更改为 FETCH JOIN 来更改此行为。
SELECT DISTINCT county FROM Event event JOIN FETCH event.count county ORDER BY county.county
“获取”连接允许使用单个选择来初始化值的关联或集合及其父对象。
更多内容请点击以下链接