Positional or named parameters can be used in WHERE
or HAVING
clauses of a query. This enables the same query to be re-executed a number of times with different parameters.
Parameters are designated by a question mark prefix followed by an integer, numbered starting from 1.
For example, the following query uses two positional parameters:
SELECT c FROM Customer c WHERE c.firstName LIKE ?1 AND c.lastName LIKE ?2
The Query.setParameter()
method is used to bind actual values to the positional parameters. The first argument of setParameter()
is an integer denoting the parameter position, the second argument is the actual value. The following listing shows how we might wrap the above query into a method which creates and executes the query:
public List<Customer> parameterQuery(String firstParam, String secondParam) { return (List<Customer>) em.createQuery( "SELECT c FROM Customer c WHERE " + "c.firstName LIKE ?1 " + "AND c.lastName LIKE...