JPA Named Queries

With the JPA1 API you can either define a query at runtime, or define it in the MetaData/annotations for a class and refer to it at runtime using a symbolic name. This second option means that the method of invoking the query at runtime is much simplified. To demonstrate the process, lets say we have a class called Product (something to sell in a store). We define the JPA Meta-Data for the class in the normal way, but we also have some query that we know we will require, so we define the following in the Meta-Data.

<entity class="Product">
    ...
    <named-query name="SoldOut"><![CDATA[
    SELECT p FROM Product p WHERE p.status == "Sold Out"
    ]]></named-query>
</entity>

So we have a JPQL query called "SoldOut" defined for the class Product that returns all Products (and subclasses) that have a status of "Sold Out". Out of interest, what we would then do in our application to execute this query woule be

Query query = em.createNamedQuery("SoldOut");
List results = query.getResultList();

The above example was for the JPQL query language. We can do a similar thing using SQL, so we define the following in our MetaData for our Product class

<entity class="Product">
    ...
    <named-native-query name="PriceBelowValue"><![CDATA[
    SELECT NAME FROM PRODUCT WHERE PRICE < ?1
    ]]></named-native-query>
</entity>

So here we have an SQL query that will return the names of all Products that have a price less than a specified value. This leaves us the flexibility to specify the value at runtime. So here we run our named query, asking for the names of all Products with price below 20 euros.

Query query = em.createNamedNativeQuery("PriceBelowValue");
query.setParameter(1, new Double(20.0));
List results = query.getResultList();


All of the examples above have been specifed within the <entity> element of the MetaData. You can also define these named queries in annotations in the class itself, but clearly that is polluting your model.

Please proceed to the sections specific to JPQL and SQL for details on the precise nature of the query for the querying languages supported by DataNucleus with JPA.