使用JPA和Hibernate时JOIN和JOIN FETCH有什么区别 [英] What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

查看:175
本文介绍了使用JPA和Hibernate时JOIN和JOIN FETCH有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我了解在哪里使用常规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条件(您可能需要),我建议您阅读此链接:

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并且继续返回部门,那是因为您在Employee和Department(a @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有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆