JPA中使用@Query註解多表聯查

原生SQL:hibernate

select `user`.id, `user`.`name`,dept.name deptName,sum(sd.score) SumScore對象

from `user`io

LEFT JOIN
score_detail sd
ON
`user`.id = sd.user_id ast

LEFT JOIN
department dept
ON
`user`.department_id = dept.idList

GROUP BY `user`.`id` ORDER BY sum(sd.score);select

 

通過查閱多方資料得知,異常

異常: org.hibernate.hql.ast.QuerySyntaxException: Path expected for joinco

 

HQL是面向對象的,因此join的條件是反映在對象的關係中的,因此,你在用join的時候,不管是left join仍是right join,都是join

FROM DomainA a LEFT JOIN a.b b WHEREtar

或者

FROM DomainA a RIGHT JOIN a.b b WHERE

而不能直接是兩個對象直接JOIN。

 

最終結果:

@Query("SELECT NEW com.ygsm.pojo.vo.SumScoreRankVO(u.id, u.name, d.name, SUM(s.score)) " + "FROM ScoreDetail s " + "RIGHT JOIN s.user u " + "RIGHT JOIN u.department d " + "WHERE s.createDate BETWEEN ?1 AND ?2 " + "GROUP BY u.id " + "ORDER BY SUM(s.score) DESC") List<SumScoreRankVO> findUserScoreRank(Date startDate, Date endDate);

相關文章
相關標籤/搜索