background image

Queries That Navigate to Related Entities

<< ExampleQueries | Traversing Relationships with an Input >>
<< ExampleQueries | Traversing Relationships with an Input >>

Queries That Navigate to Related Entities

See also
:
"Input Parameters" on page 752
,
"The DISTINCT Keyword" on page 761
Using Named Parameters
SELECT DISTINCT p
FROM Player p
WHERE p.position = :position AND p.name = :name
Data retrieved
: The players having the specified positions and names.
Description
: The position and name elements are persistent fields of the Player entity. The
WHERE
clause compares the values of these fields with the named parameters of the query, set
using the Query.setNamedParameter method. The query language denotes a named input
parameter using colon (:) followed by an identifier. The first input parameter is :position, the
second is :name.
Queries That Navigate to Related Entities
In the query language, an expression can traverse (or navigate) to related entities. These
expressions are the primary difference between the Java Persistence query language and SQL.
Queries navigates to related entities, whereas SQL joins tables.
A Simple Query with Relationships
SELECT DISTINCT p
FROM Player p, IN(p.teams) t
Data retrieved
: All players who belong to a team.
Description
: The FROM clause declares two identification variables: p and t. The p variable
represents the Player entity, and the t variable represents the related Team entity. The
declaration for t references the previously declared p variable. The IN keyword signifies that
teams
is a collection of related entities. The p.teams expression navigates from a Player to its
related Team. The period in the p.teams expression is the navigation operator.
You may also use the JOIN statement to write the same query:
SELECT DISTINCT p
FROM Player p JOIN p.teams t
This query could also be rewritten as:
SELECT DISTINCT p
FROM Player p
WHERE p.team IS NOT EMPTY
Example Queries
The Java EE 5 Tutorial · September 2007
736