Book Image

EJB 3 Developer Guide

By : Michael Sikora
Book Image

EJB 3 Developer Guide

By: Michael Sikora

Overview of this book

Table of Contents (18 chapters)
EJB 3 Developer Guide
Credits
About the Author
About the Reviewers
Preface
Annotations and Their Corresponding Packages

Queries with Parameters


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.

Positional 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...