Java Reference
In-Depth Information
The
getCustomers()
method is expanded as compared to previous examples in this topic.
The
firstName
and
lastName
query parameters are added. This allows clients to search for
customers in the database with a specific first and last name.
Query query
=
null
null
;
iif
(
firstName
!=
null
null
&&
lastName
!=
null
null
)
{
query
=
em
.
createQuery
(
"select c from Customer c where c.firstName=:first
and c.lastName=:last"
);
query
.
setParameter
(
"first"
,
firstName
);
query
.
setParameter
(
"last"
,
lastName
);
}
else
else
if
(
lastName
!=
null
null
)
{
query
=
em
.
createQuery
(
"select c from Customer c where c.lastName=:last"
);
query
.
setParameter
(
"last"
,
lastName
);
}
else
else
{
query
=
em
.
createQuery
(
"select c from Customer c"
);
}
The
getCustomers()
method builds a JPA query based on the values of
firstName
and
lastName
. If these are both set, it searches in the database for all customers with that first
and last name. If only
lastName
is set, it searches only for customers with that last name.
Otherwise, it just queries for all customers in the database.
List customerEntities
=
query
.
setFirstResult
(
start
)
.
setMaxResults
(
size
)
.
getResultList
();
Next, the code executes the query. You can see that doing paging is a little bit easier with JPA
query.setFirstResult()
methods set the index and size of the dataset you want returned.
for
for
(
Object obj
:
customerEntities
)
{
CustomerEntity entity
= (
CustomerEntity
)
obj
;
list
.
add
(
entity2domain
(
entity
));
}