1
votes

I'm learning Hibernate and I'm wondering what's the use of the JOIN clause within a HQL query. I might be wrong, but it seems to me that you can always do without.

Let's say I have a ChildClass entity which has a mapped @ManyToOne relationship with a ParentClass.

Now I can build a HQL query like this:

session.createQuery("FROM ChildClass ch WHERE ch.parentClass.id=1L")

As you can see I could filter the results by the parent class' id field, accessing it through the child class: ch.parentClass.id

If I wanted to do the same in SQL, I'd need to perform a JOIN, and the query would be the following:

SELECT * FROM ChildTable ch
JOIN ParentTable p ON (ch.parent_id = p.id)
WHERE p.id=1;

If I got this straight, in HQL I don't need to include any JOIN in my query, because the @ManyToOne mapped relationship implicitly joins the two entities. So why would I ever use JOIN in a HQL query? Is there any specific kind of situations where JOIN is necessary?

1

1 Answers

2
votes

There are several situations where explicitly specifying the join is useful

  1. You want to specify a different join-type than the mapping, e.g. INNER vs OUTER.
  2. You want to specify a join-fetch scenario where not only do you want to join the association but you'd also like the query results to fetch the association too.