I have a Report
entity that has a list of ReportedTime
as @OneToMany
relation. Each ReportedTime
has a project, and Project
has a manager.
The query itself (shown at the bottom) works fine. The problem is I need to now map these entities to DTOs and for that mapping purpose I need to know the projects that are in each ReportedTime
in each Report
. So I'm facing an n+1 problem, and I wanted to join fetch the reportedTimes and projects:
@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);
but I get this error:
org.postgresql.util.PSQLException: ERROR: column "reportedtimes1_.id" must appear in the GROUP BY clause or be used in an aggregate function
I tried to see the sql query in the logs and it seems that in this scenario Hibernate also puts the reported_time.id and project.id in the select clause but does not know how to group it? Is there way around this?