请帮助我了解在何处使用常规 JOIN 以及在何处使用 JOIN FETCH.
Please help me understand where to use a regular JOIN and where a JOIN FETCH.
例如,如果我们有这两个查询
For example, if we have these two queries
FROM Employee emp JOIN emp.department dep和
FROM Employee emp JOIN FETCH emp.department dep它们之间有什么区别吗?如果是,什么时候使用哪个?
Is there any difference between them? If yes, which one to use when?
推荐答案在这两个查询中,您将使用 JOIN 查询至少与一个部门相关联的所有员工.
In this two queries, you are using JOIN to query all employees that have at least one department associated.
但是,不同之处在于:在第一个查询中,您只返回 Hibernate 的 Employes.在第二个查询中,您将返回员工和关联的所有部门.
But, the difference is: in the first query you are returning only the Employes for the Hibernate. In the second query, you are returning the Employes and all Departments associated.
因此,如果您使用第二个查询,您将不需要执行新查询来再次访问数据库以查看每个员工的部门.
So, if you use the second query, you will not need to do a new query to hit the database again to see the Departments of each Employee.
当您确定需要每个员工的部门时,可以使用第二个查询.如果您不需要部门,请使用第一个查询.
You can use the second query when you are sure that you will need the Department of each Employee. If you not need the Department, use the first query.
如果您需要应用一些 WHERE 条件(您可能需要什么),我建议阅读此链接:如何正确表达JPQLjoin fetch"用哪里"子句作为 JPA 2 CriteriaQuery?
I recomend read this link if you need to apply some WHERE condition (what you probably will need): How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?
更新
如果你不使用fetch而Departments继续返回,是因为你的Employee和Department之间的映射(一个@OneToMany)是用FetchType.EAGER.在这种情况下,任何带有 FROM Employee 的 HQL(带 fetch 或不带)查询都会带上所有部门.请记住,所有映射 *ToOne(@ManyToOne 和 @OneToOne)在默认情况下都是 EAGER.
If you don't use fetch and the Departments continue to be returned, is because your mapping between Employee and Department (a @OneToMany) are setted with FetchType.EAGER. In this case, any HQL (with fetch or not) query with FROM Employee will bring all Departments. Remember that all mapping *ToOne (@ManyToOne and @OneToOne) are EAGER by default.
更多推荐
使用JPA和Hibernate时JOIN和JOIN FETCH有什么区别
发布评论