Skip Headers
Oracle® Containers for J2EE Enterprise JavaBeans Developer's Guide
10g (10.1.3.1.0)

Part Number B28221-02
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Index
Index
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
View PDF

Implementing a JPA Named Query

A named query is a predefined query that you create and associate with a container-managed entity (see "Using Annotations"). At deployment time, OC4J stores named queries on the EntityManager. At run time, you can use the EntityManager to acquire, configure, and execute a named query.

For more information, see the following:

Using Annotations

Example 8-1 shows how to use the @NamedQuery annotation to define a Java persistence query language query that you can acquire by name findAllEmployeesByFirstName at run time using the EntityManager.

Example 8-1 Implementing a Query Using @NamedQuery

@Entity
@NamedQuery(
    name="findAllEmployeesByFirstName",
    queryString="SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName = 'John'"
)
public class Employee implements Serializable {
...
}

Example 8-2 shows how to use the @NamedQuery annotation to define a Java persistence query language query that takes a parameter named firstname. Example 8-3 shows how you use the EntityManager to acquire this query and use Query method setParameter to set the firstname parameter. For more information on using the EntityManager with named queries, see "Querying for a JPA Entity Using the EntityManager".

Optionally, you can configure your named query with query hints to use JPA persistence provider vendor extensions (see "Configuring TopLink Query Hints in a JPA Query").

Example 8-2 Implementing a Query With Parameters Using @NamedQuery

@Entity
@NamedQuery(
    name="findAllEmployeesByFirstName",
    queryString="SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName = :firstname"
)
public class Employee implements Serializable {
...
}

Example 8-3 Setting Parameters in a Named Query

Query queryEmployeesByFirstName = em.createNamedQuery("findAllEmployeesByFirstName");
queryEmployeeByFirstName.setParameter("firstName", "John");
Collection employees = queryEmployessByFirstName.getResultList();