Queries

Queries return entities matching certain criteria. In ObjectBox you can formulate queries easily with the QueryBuilder API.

QueryBuilder

The QueryBuilder<T> class together with the properties class generated for each entity lets you build custom queries for your entities.

Simple condition example: Query for all users with the first name “Joe”:

Multiple conditions example: Get users with the first name “Joe” that are born later than 1970 and whose last name starts with “O”.

Query

The Query<T> class represents a query that can be executed multiple times. It is created (and not yet executed) by calling build() on the QueryBuilder<T>.

To return all entities matching the query simply call find().

To only return the first result, use findFirst().

If you expect a unique result call findUnique() instead. It will give you a single result or null, if no matching entity was found and throw an exception if there was more than one result.

Limit, Offset, and Pagination

Sometimes you only need a subset of a query, for example the first 10 elements to display in your user interface. This is especially helpful (and resourceful) when you have a high number of entities and you cannot limit the result using query conditions only. The built Query has a .find(int offset, int limit) method with offset and limit arguments:

offset: The first offset results are skipped.

limit: At most limit results of this query are returned.

Executing Queries multiple times

Once you built a query using the QueryBuilder, the Query object can be reused to execute the query later. This is more efficient than always creating new Query objects. If the query parameters don’t change you can just call one of the find methods again.

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •