Here's a collection of native query examples. These queries assume that there's a Pilot class with a name and age and a Car class with a pilot and name.
This query shows you how compare a getter/setter for equality. In this example we compare the name of a person.
ObjectSet<Pilot> result = container.query(new Predicate<Pilot>() { @Override public boolean match(Pilot pilot) { return pilot.getName().equals("John"); } });
You can compare values with the usual comparison operators.
ObjectSet<Pilot> result = container.query(new Predicate<Pilot>() { @Override public boolean match(Pilot pilot) { return pilot.getAge() > 18; } });
Of course you can combine different comparisons. For example you can combine the greater and smaller than operators to check for a range of values.
ObjectSet<Pilot> result = container.query(new Predicate<Pilot>() { @Override public boolean match(Pilot pilot) { return pilot.getAge() > 18 && pilot.getAge()<30; } });
Of course you can combine a arbitrary set of conditions with logical operators.
ObjectSet<Pilot> result = container.query(new Predicate<Pilot>() { @Override public boolean match(Pilot pilot) { return (pilot.getAge() > 18 && pilot.getAge()<30) || pilot.getName().equals("John"); } });
You can implement your query in a separate class and then just us it where you need it. This is especially useful when you reuse the same query multiple times. Or you want to give your query a clear name for documentation purposes.
First write your class:
class AllJohns extends Predicate<Pilot> { @Override public boolean match(Pilot pilot) { return pilot.getName().equals("John"); } }
And then use it:
ObjectSet<Pilot> result = container.query(new AllJohns());
In principal your query can contain any code and can do the most complex comparisons. However in practice the are limitations. The simple queries are optimized and translated to SODA-queries. This is not possible for complex queries. If the query cannot be optimized, db4o will instantiate all objects and pass it to your query-object. This is a order of magnitude slower than a optimized native query and only feasible for smaller data sets.
final List<Integer> allowedAges = Arrays.asList(18,20,33,55); ObjectSet<Pilot> result = container.query(new Predicate<Pilot>() { @Override public boolean match(Pilot pilot) { return allowedAges.contains(pilot.getAge()) || pilot.getName().toLowerCase().equals("John"); } });