[英]Using join fetch and group by in HQL query
我有一個Report
實體,它有一個ReportedTime
列表作為@OneToMany
關系。 每個ReportedTime
都有一個項目,而Project
有一個經理。
查詢本身(顯示在底部)工作正常。 問題是我現在需要映射這些實體的DTO並為測繪目的,我需要知道,在每個項目ReportedTime
在每個Report
。 所以我面臨 n+1 問題,我想加入獲取報告時間和項目:
@Query(value = "select " +
"t as timesheetReport, " +
"FUNCTION('string_agg', tlpa.username, ',') as projectManagersUsernames, " +
"case when " +
" FUNCTION('string_agg', tlpa.username, ',') like concat('%', :username, '%') " +
"then true else false " +
"end as assigned " +
"from TimesheetReport t " +
"left join fetch t.reportedTimes rt " +
"left join fetch rt.project p " +
"left join p.teamLeaderAssignments tlp " +
"left join tlp.account tlpa " +
"group by t " +
"having sum(rt.workTime)>0 " +
"order by assigned desc ")
List<IReportWithManagers> findAllWithManagers(String username, Pageable pageable);
但我收到此錯誤:
org.postgresql.util.PSQLException: ERROR: column "reportedtimes1_.id" must appear in the GROUP BY clause or be used in an aggregate function
我試圖在日志中查看 sql 查詢,似乎在這種情況下,Hibernate 也在 select 子句中放置了reported_time.id和project.id,但不知道如何對其進行分組? 有沒有辦法解決這個問題?
您收到錯誤是因為,當然,在獲取連接的實體時,您突然嘗試選擇一大堆既不包含在GROUP BY
也不包含在聚合中的新列。
為了能夠從rt
和p
選擇列,您需要GROUP BY t, rt, p
,不幸的是(據我所知)改變了查詢的語義。 我會嘗試添加單獨的JOINS
來獲取和分組:
left join t.reportedTimes rt
left join rt.project p
left join fetch t.reportedTimes rt2
left join fetch rt.project p2
left join p.teamLeaderAssignments tlp
left join tlp.account tlpa
group by t, rt2, p2
having sum(dt.workTime)>0
order by assigned desc
上面的問題是,重復的行現在將進入聚合,所以也許您可以使用ARRAY_TO_STRING(ARRAY_AGG(DISTINCT tlpa.username, ',')
或選擇數組並在 Java 中加入字符串(不確定 Hibernate 是否支持選擇不過,PostgreSQL 數組是開箱即用的,您需要檢查一下)。
請注意,我還沒有嘗試過上述解決方案,所以我不能保證它會起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.