|
SimpleQuery
How to run queries against the datastore
SimpleQuerySimpleQuery is a wrapper class that enhances the capabilities of the Query class with a simpler method signature and adds the FetchOptions method for a more convenient Query creation interface. List<Model> l = entityManager.createQuery(Model.class)
.equal("name", "foo")
.lessThanOrEqual("intValue", 5)
.asList();The filter operations equal(), notEqual(), lessThan(), lessThanOrEqual(), greaterThan(), greaterThanOrEqual(), isNull(), isNotNull() and in() are supported. Left like is supported: // name like 'John%'
query.like("name", "John");When adding filter clauses null values will be ignored so you don't have to check your values before submitting. This means that query.equal(propertyName, null) will be skipped; if you want to compare a property with null, use isNull(propertyName). You can also specify query limits or retrieve just the key values: List<Key> keys = new SimpleQuery(Bird.class) .withLimit(100) .keysOnly() .asList(); SimpleQuery implements Cloneable, which means that you can create a query and then clone() it to reuse several times. To optimize performance, SimpleQuery.count() will clone the query instance and invoke keysOnly() automatically, if needed. Queries can be cached (see Cache). Result TypesOnce configured, your query can be executed to return different kind of result types: // return a single result
User u = entityManager.createQuery(User.class)
.equal("email", "a@b.c")
.asSingleResult();
// return a list of results (use with care)
List<User> users = entityManager.createQuery(User.class)
.asList();CursorsCursors can be used to resume a query at the last known position. The easiest way to use cursors is via the related CursorList class: // return a page of 20 users _and_ the cursor at the end of the list
CursorList<User> page1 = entityManager.createQuery(User.class)
.lessThan("creationTimestamp", until)
.asCursorList(20);
// return the next page of results
CursorList<User> page2 = entityManager.createQuery(User.class)
.lessThan("creationTimestamp", until)
.withStartCursor(page1.getCursor())
.asCursorList(20);To obtain a cursor instance you can also use asIterable() and asIterator(): SimpleQueryResultIterator<Data> data = query.asIterable(); Data d1 = data.next(); Data d2 = data.next(); Cursor cursor = data.getCursor(); To resume a query with a cursor: SimpleQuery query = entityManager.createQuery(Data.class).withStartCursor(cursor); Remember that cursors do not include the parameters used in a query but just the position. When using cursors you must provide every query parameter with the same value. |