Cover by Dan Sanderson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

The Java Query API

If you are using the JPA interface or the JDO interface, you will use the query facilities of those interfaces to perform datastore queries: JPQL or JDOQL, respectively. The concepts of those interfaces map nicely to the concepts of datastore queries: a query has a kind (a class), filters, and sort orders. We’ll look at the calling conventions for JPQL when we look at JPA in Chapter 8.

Naturally, the low-level Java datastore API includes a query interface as well. Here is a brief example:

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

// ...
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        
        Query q = new Query("Book");
        q.addFilter("copyrightYear",
                    Query.FilterOperator.LESS_THAN_OR_EQUAL,
                    1950);
        q.addSort("title");

        PreparedQuery pq = ds.prepare(q);
        for (Entity result : pq.asIterable()) {
            String title = result.getProperty("title");

            // ...
        }

To perform a query, you instantiate the Query class (from the com.google.appengine.api.datastore package), providing the name of the kind of the entities to query as an argument to the constructor. You call methods on the query object to add filters and sort orders. To perform the query, you pass the query object to a method of the DatastoreService instance. This method returns ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required