问题描述
请帮助我了解在哪里使用常规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.
但是,区别是:在第一个查询中,您仅返回休眠的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条件(您可能需要),我建议您阅读此链接:
这篇关于使用JPA和Hibernate时JOIN和JOIN FETCH有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!