JPQL LEFT JOIN不起作用

时间:2017-04-12 03:14:06

标签: jpql

我想获取所有Branch的列表,即使他们没有user角色的帐户

Query query = em.createQuery("SELECT NEW com.package.BranchInstructors(b,a) FROM Branch b LEFT JOIN b.accounts a WHERE b.dFlg = 0 AND a.userRole = :role ORDER BY b.name ASC");
query.setParameter("role", "user");
return query.getResultList();

不幸的是,它只返回user角色的分支机构,而不是像INNER JOIN那样。

知道发生了什么事吗?

2 个答案:

答案 0 :(得分:1)

只需在查询中添加a.userRole is null条件,以避免过滤从左连接中获得的null userRole

 SELECT NEW com.package.BranchInstructors(b,a) 
     FROM Branch b
     LEFT JOIN b.accounts a
     WHERE b.dFlg = 0 
     AND (a.userRole = :role OR a.userRole IS NULL)
     ORDER BY b.name ASC"

答案 1 :(得分:0)

问题出在您的WHERE vs LEFT JOIN条款中。

如果您使用LEFT JOINAccounts并在WHERE AND条件下使用此表,则其行为类似于JOIN

因此,您可以在WITH中使用LEFT JOIN

Query query = em.createQuery("SELECT NEW com.package.BranchInstructors(b,a) FROM Branch b 
LEFT JOIN b.accounts a WITH a.userRole = :role
WHERE b.dFlg = 0 ORDER BY b.name ASC");