使用JPA和Hibernate时JOIN和JOIN FETCH有什么区别

编程入门 行业动态 更新时间:2024-10-27 20:31:16
本文介绍了使用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.

但是,不同之处在于:在第一个查询中,您只返回 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有什么区别

本文发布于:2023-11-24 19:04:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626455.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   Hibernate   JPA   FETCH   JOIN

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!