Using Evaluations

For a simple example, let's take a Car class keeping a history of SensorReadout instances in a List member. Now imagine that we wanted to retrieve all cars that have assembled an even number of history entries. A quite contrived and seemingly trivial example, however, it gets us into trouble: Collections are transparent to the query API, it just 'looks through' them at their respective members.

So how can we get this done? Let's implement an Evaluation that expects the objects passed in to be instances of type Car and checks their history size.

EvenHistoryEvaluation.java
01package com.db4odoc.f1.evaluations; 02 03import com.db4o.query.*; 04 05 06public class EvenHistoryEvaluation implements Evaluation { 07 public void evaluate(Candidate candidate) { 08 Car car=(Car)candidate.getObject(); 09 candidate.include(car.getHistory().size() % 2 == 0); 10 } 11}

To test it, let's add two cars with history sizes of one and two respectively:

EvaluationExample.java: storeCars
01public static void storeCars(ObjectContainer db) { 02 Pilot pilot1=new Pilot("Michael Schumacher",100); 03 Car car1=new Car("Ferrari"); 04 car1.setPilot(pilot1); 05 car1.snapshot(); 06 db.set(car1); 07 Pilot pilot2=new Pilot("Rubens Barrichello",99); 08 Car car2=new Car("BMW"); 09 car2.setPilot(pilot2); 10 car2.snapshot(); 11 car2.snapshot(); 12 db.set(car2); 13 }

and run our evaluation against them:

EvaluationExample.java: queryWithEvaluation
1public static void queryWithEvaluation(ObjectContainer db) { 2 Query query=db.query(); 3 query.constrain(Car.class); 4 query.constrain(new EvenHistoryEvaluation()); 5 ObjectSet result=query.execute(); 6 listResult(result); 7 }