If we just want to retrieve the first and last name of Customer entities, we could use projection in JPQL as follows:
SELECT c.firstName, c.lastName FROM Customer c
The variables c.firstName
and c.lastName
are examples of a JPQL path expression. A path expression is an identification variable followed by the navigation operator (.) and a state-field or association-field. Persistent fields of the Customer entity such as firstName
and lastName
are examples of state-fields. We shall see examples of path expressions with association-fields later in this chapter.
In the above query a list of Object arrays, rather than Customer entities, is returned. The following code shows how we might print out the results of our query:
List<Object[]> names = query.getResultList(); for (Object[] name : names) { System.out.println("First Name: " + name[0] + "Last Name: " + name[1]); }
To remove duplicate values the DISTINCT
operator is used:
SELECT DISTINCT c.lastName FROM Customer c
In this...