Laird Nelson
Laird Nelson

Reputation: 16238

When is an explicit JOIN required in JPQL?

Consider the following JPA 2.0-compliant JPQL queries:

SELECT p
  FROM PostalAddress p
  JOIN p.constituent c
 WHERE c.id = :constituentId
 ORDER BY p.type.displayOrder

...and:

SELECT p
  FROM PostalAddress p
  JOIN p.constituent c
  JOIN p.type t
 WHERE c.id = :constituentId
 ORDER BY t.displayOrder

In both cases, p.type is a @ManyToOne relationship with another entity (PostalAddressType).

The difference in the two queries is that in the first one there is no explicit JOIN from PostalAddress to PostalAddressType. It is implied, I guess, through the p.type.displayOrder snippet in the WHERE clause. In the second, there is an explicit JOIN.

Are these queries equivalent?

Are they also equivalent to:

SELECT p
  FROM PostalAddress p
 WHERE p.constituent.id = :constituentId
 ORDER BY p.type.displayOrder

...?

It seems so. In these cases, do the explicit JOINs (between PostalAddress and Constituent, and between PostalAddress and PostalAddressType) help in any way (other than readability and explicitness)?

For completeness, I understand that a JOIN is always required if a path expression evaluates to a collection; I'm not (at the moment :-)) interested in that case.

Upvotes: 3

Views: 695

Answers (1)

JB Nizet
JB Nizet

Reputation: 692073

It's required each time you want a left join and not an inner join.

Upvotes: 4

Related Questions