Skip Headers
Oracle® Containers for J2EE Enterprise JavaBeans Developer's Guide
10g Release 3 (10.1.3)
B14428-01
  Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index

Previous
Previous
Next
Next
 

Implementing an EJB 3.0 Named Query

A named query is a pre-defined query that you create and associate with a CMP entity (see "Using Annotations"). At deployment time, OC4J stores named queries on the EntityManager (see "How Do You Query for an EJB 3.0 Entity?").

At runtime, you can use the EntityManager to acquire, configure, and execute a named query (see "Querying for an EJB 3.0 Entity Using the EntityManager").


Note:

In this release, OC4J does not support EJB 3.0 named queries using native SQL. For more information, see "Understanding Native SQL Query Syntax".

Using Annotations

Example 8-1 shows how to use the @NamedQuery annotation to define an EJB QL query that you can acquire by name findAllEmployeesByFirstName at runtime 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 an EJB QL 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 an EJB 3.0 Entity Using the EntityManager".

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();