[英]Why JPA query left join on codition not working?
I'm using Hibernate as JPA implementation and have two tables: User
and Agency
.我使用 Hibernate 作为 JPA 实现并有两个表:
User
和Agency
。
Each Agency
can have many users.每个
Agency
可以有许多用户。 A User
can have one or zero Agency
一个
User
可以有一个或零个Agency
User
public class User {
@Id
private String userId;
@ManyToOne
@JoinColumn(nullable=true)
@NotFound(action=NotFoundAction.IGNORE)
private Agency agency;
}
Agency
public class Agency {
@Id
private String agencyCd;
private String delFlg; //0 means in use
@OneToMany(mappedBy="agency")
private List<User> userList;
}
In the repository, query is在存储库中,查询是
@Query("SELECT DISTINCT u FROM User u LEFT JOIN u.agency a on a.delFlg='0')
My problem is, left join on codition(a.delFlg='0') is not working.我的问题是,左加入 codition(a.delFlg='0') 不起作用。
Agencies with delFlg is 1 are all included in the results. delFlg 为 1 的机构都包含在结果中。
How can I find user with left joined agencies whose delFlg
is 0?如何找到
delFlg
为 0 的左加入代理机构的用户?
It seems your case is explicitly described in the JPA Specification 4.2 Section 4.4.5.2您的情况似乎在 JPA 规范 4.2 第 4.4.5.2 节中明确描述
An outer join without a specified join condition has an implicit join condition over the foreign key relationship corresponding to the join_association_path_expression .
没有指定连接条件的外连接在与join_association_path_expression对应的外键关系上具有隐式连接条件。 It would typically be mapped to a SQL outer join with an ON condition on the foreign key relationship as in the queries below: Java Persistence query language:
它通常会映射到 SQL 外连接,外键关系上有一个 ON 条件,如下面的查询所示: Java 持久性查询语言:
SELECT s.name, COUNT(p) FROM Suppliers s LEFT JOIN s.products p GROUP BY s.name
SQL:
SQL:
SELECT s.name, COUNT(p.id) FROM Suppliers s LEFT JOIN Products p ON s.id = p.supplierId GROUP By s.name
An outer join with an explicit ON condition would cause an additional specified join condition to be added to the generated SQL: Java Persistence query language:
具有显式 ON 条件的外连接会导致将额外的指定连接条件添加到生成的 SQL:Java 持久性查询语言:
SELECT s.name, COUNT(p) FROM Suppliers s LEFT JOIN s.products p ON p.status = 'inStock' GROUP BY s.name
SQL:
SQL:
SELECT s.name, COUNT(p.id) FROM Suppliers s LEFT JOIN Products p ON s.id = p.supplierId AND p.status = 'inStock' GROUP BY s.name
Note that the result of this query will be different from that of the following query: SELECT s.name, COUNT(p) FROM Suppliers s LEFT JOIN s.products p WHERE p.status = 'inStock' GROUP BY s.name The result of the latter query will exclude suppliers who have no products in stock whereas the former query will include them.
请注意,此查询的结果将与以下查询的结果不同: SELECT s.name, COUNT(p) FROM Suppliers s LEFT JOIN s.products p WHERE p.status = 'inStock' GROUP BY s.name 结果后一个查询将排除没有库存产品的供应商,而前一个查询将包括它们。
So your query should probably be:所以你的查询应该是:
SELECT u
FROM User u
LEFT JOIN u.agency a
WHERE a IS NULL
OR a.delFlg='0'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.