17.4. Named SQL Queries
Prev | Chapter 17. SQL Queries | Next

## 17.4. Named SQL Queries

We discussed how to write named JDOQL queries in Section 11.10, “Named Queries”. Named queries, however, are not limited to JDOQL. By setting the `query` element's `language` attribute to `javax.jdo.query.SQL`, you can define a named SQL query. A named SQL query within a `class` element queries for instances of that class; a named SQL query outside of a `class` element acts as a column data projection.

Example 17.7. Named SQL Queries

    <?xml version="1.0"?>
    <jdoquery>
        <query name="salesReport" language="javax.jdo.query.SQL">
            SELECT TITLE, PRICE * COPIES FROM MAG
        </query>
        <package name="org.mag">
            <class name="Magazine">
                <query name="findByTitle" language="javax.jdo.query.SQL">
                    SELECT * FROM MAG WHERE TITLE = ?
                </query>
            </class>
        </package>
    </jdoquery>

The `salesReport` query above returns the title and revenue generated for each `Magazine`. Because it is a projection, it does not have a candidate class, and so we specify it at the root level.

The `findByTitle` query returns the `Magazine` with the title given on execution. The code below executes both queries.

    PersistenceManager pm = ...;
    Query query = pm.newNamedQuery (null, "salesReport");
    List sales = (List) query.execute ();
    for (Iterator itr = sales.iterator (); itr.hasNext ();)
    {
        Object[] salesData = (Object[]) itr.next ();
        processSalesData ((String) salesData[0], (Number) salesData[1]);
    }
    query.close (sales);

    query = pm.newNamedQuery (Magazine.class, "findByTitle");
    query.setUnique (true);
    Magazine jdj = (Magazine) query.execute ("JDJ");

Prev | Up | Next
17.3. SQL Projections | Home | 17.5. Conclusion