With the JDO2 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 JDO 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.
<jdo>
<package name="org.datanucleus.example">
<class name="Product">
...
<query name="SoldOut" language="javax.jdo.query.JDOQL"><![CDATA[
SELECT FROM org.datanucleus.example.Product WHERE status == "Sold Out"
]]></query>
</class>
</package>
</jdo>
So we have a JDOQL 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=pm.newNamedQuery(org.datanucleus.example.Product.class,"SoldOut");
Collection results=(Collection)query.execute();
The above example was for the JDOQL object-based query language. We can do a similar thing using SQL, so we define
the following in our MetaData for our
Product
class
<jdo>
<package name="org.datanucleus.example">
<class name="Product">
...
<query name="PriceBelowValue" language="javax.jdo.query.SQL"><![CDATA[
SELECT NAME FROM PRODUCT WHERE PRICE < ?
]]></query>
</class>
</package>
</jdo>
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=pm.newNamedQuery(org.datanucleus.example.Product.class,"PriceBelowValue");
Collection results=(Collection)query.execute(20.0);
All of the examples above have been specifed within the <class> element of the MetaData. You can, however,
specify queries below <jdo> in which case the query is not scoped by a particular candidate class. In this case
you must put your queries in any of the following MetaData files
/META-INF/package.jdo
/WEB-INF/package.jdo
/package.jdo
/META-INF/package-{mapping}.orm
/WEB-INF/package-{mapping}.orm
/package-{mapping}.orm
/META-INF/package.jdoquery
/WEB-INF/package.jdoquery
/package.jdoquery
Please proceed to the sections specific to
JDOQL
and
SQL
for details on the precise nature of the query for the querying languages
supported by DataNucleus.