Queries return entities matching certain criteria. In ObjectBox you can formulate queries easily with the QueryBuilder API.
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”:
List<User> joes = userBox.query()
Multiple conditions example: Get users with the first name “Joe” that are born later than 1970 and whose last name starts with “O”.
QueryBuilder<User> builder = userBox.query();
List<User> youngJoes = builder.build().find();
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>.
Query<User> query = builder.build();
// return all entities matching the query
List<User> joes = query.find();
// return only the first result or null if none
User joe = query.findFirst();
// return the only result or null if none, throw if more than one result
User joe = query.findUnique();
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:
Query<User> query = userBox.query().equal(UserProperties.FirstName, "Joe").build();
List<User> joes = query.find(10 /** offset by 10 */, 5 /** limit to 5 results */);
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.