FROM Employee emp JOIN emp.department dep FROM Employee emp JOIN emp.department dep
and
FROM Employee emp JOIN FETCH emp.department dep FROM Employee emp JOIN FETCH emp.department dep
Is there any difference between them? If yes, which one to use when? 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.
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.