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, it 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.