Java Reference
In-Depth Information
SELECT u
FROM User u INNER JOIN u.Category c
WHERE u.userId LIKE ?1
The
INNER
clause is optional. Remember that
INNER JOIN
is the default when you use
the
JOIN
operator by itself, without specifying
INNER
or
OUTER
. Now let's move to the
other end of the spectrum: outer joins.
Outer joins
Outer joins allow you to retrieve additional entities that don't match the
JOIN
conditions
when associations between entities are optional. Outer joins are particularly useful in re-
porting. Assume that there's an optional relationship between
User
and
Category
and
you want to generate a report that prints all the category names for the user. If the user
doesn't have any categories, then you want to print
NULL
. If you specify the user on the left
side of the
JOIN
, you can use either the
LEFT JOIN
or
LEFT OUTER JOIN
keyword
phrases with a JPQL query as follows:
SELECT u
FROM User u LEFT OUTER JOIN u.Category c
WHERE u.userId like ?1
This will also retrieve
User
entities that don't have a matching
Category
, as well as
those who do. It's worth noting that if an outer join isn't used, the query would only re-
trieve the users with the matching category but would fail to retrieve users that didn't have
a matching category.
Although
INNER JOIN
and
OUTER JOIN
are the most common, are there any other
types of
JOIN
s supported by JPQL? We're glad you asked! The answer is yes, and next
we'll look at fetch and theta joins.
Fetch joins
In a typical business application, you may want to query for a particular entity but also
retrieve its associated entities at the same time. For example, when you retrieve a
Bid
in
the ActionBazaar system, you want to eagerly load and initialize the associated instance of
bidder
. You can use a
FETCH JOIN
clause in JPQL to retrieve an associated entity as a
side effect of the retrieval of an entity: