休眠中JOIN和JOIN FETCH之间的区别 [英] Difference between JOIN and JOIN FETCH in Hibernate
问题描述
请帮助我了解在哪里使用常规JOIN和JOIN FETCH。 b
FROM雇员emp
JOIN emp.department dep
FROM雇员emp
JOIN FETCH emp.department dep
它们之间是否有区别?在这两个查询中,您正在使用JOIN查询所有员工在至少有一个部门是关联的。
但区别在于:在第一个查询中,您只返回Hibernate的Employes。在第二个查询中,您将返回所有关联的部门Employes 和。
因此,如果您使用第二个查询,则不需要重新执行查询就可以再次访问数据库,以查看每个员工的部门。
您可以在确定需要每个员工的部门时使用第二个查询。如果您不需要该部门,请使用第一个查询。
如果您需要应用一些WHERE条件(您可能需要): href =https://stackoverflow.com/questions/5816417/how-to-properly-express-jpql-join-fetch-with-where-clause-as-jpa-2-criteriaq>如何正确表达JPQL ;加入获取与where条款作为JPA 2 CriteriaQuery?
更新
不要使用 fetch
并且部门继续返回,这是因为您在Employee和Department之间的映射(a @OneToMany
)被设置为 FetchType.EAGER
。在这种情况下,任何使用 FROM Employee
的HQL(带有 fetch
或不))查询将带来所有Departments。请记住,默认情况下,所有映射* ToOne( @ManyToOne
和 @OneToOne
)都是EAGER。
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
and
FROM Employee emp
JOIN FETCH emp.department dep
Is there any difference between them? If yes, which one to use when?
In this two queries, you are using JOIN to query all employees that have at least one department associated.
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.
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?
Update
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.
这篇关于休眠中JOIN和JOIN FETCH之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!