background image

Named Parameters in Queries

<< Creating Queries | Persistence Units >>
<< Creating Queries | Persistence Units >>

Named Parameters in Queries

@NamedQuery
specifies the name of the query that will be used with the createNamedQuery
method. The query element of @NamedQuery is the query.
@NamedQuery(
name=
"findAllCustomersWithName",
query=
"SELECT c FROM Customer c WHERE c.name LIKE :custName"
)
Here's an example of createNamedQuery, which uses the @NamedQuery defined above.
@PersistenceContext
public EntityManager em;
...
customers = em.createNamedQuery(
"findAllCustomersWithName")
.setParameter(
"custName", "Smith")
.getResultList();
Named Parameters in Queries
Named parameters are parameters in a query that are prefixed with a colon (:). Named
parameters in a query are bound to an argument by the
javax.persistence.Query.setParameter(String name, Object value)
method. In the
following example, the name argument to the findWithName business method is bound to the
:custName
named parameter in the query by calling Query.setParameter.
public List findWithName(String name) {
return em.createQuery(
"SELECT c FROM Customer c WHERE c.name LIKE :custName")
.setParameter(
"custName", name)
.getResultList();
}
Named parameters are case-sensitive, and may be used by both dynamic and static queries.
Positional Parameters in Queries
You may alternately use positional parameters in queries, instead of named parameters.
Positional parameters are prefixed with a question mark (?) followed the numeric position of
the parameter in the query. The Query.setParameter(integer position, Object value)
method is used to set the parameter values.
In the following example, the findWithName business method is rewritten to use input
parameters:
public List findWithName(String name) {
return em.createQuery(
"SELECT c FROM Customer c WHERE c.name LIKE ?1")
Managing Entities
The Java EE 5 Tutorial · September 2007
700