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
01/* Copyright (C) 2004 - 2007 db4objects Inc. http://www.db4o.com */ 02package com.db4odoc.evaluations; 03 04import com.db4o.query.*; 05 06 07public class EvenHistoryEvaluation implements Evaluation { 08 public void evaluate(Candidate candidate) { 09 Car car=(Car)candidate.getObject(); 10 candidate.include(car.getHistory().size() % 2 == 0); 11 } 12}

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

EvaluationExample.java: storeCars
01private static void storeCars(ObjectContainer container) { 02 Pilot pilot1 = new Pilot("Michael Schumacher", 100); 03 Car car1 = new Car("Ferrari"); 04 car1.setPilot(pilot1); 05 car1.snapshot(); 06 container.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 container.set(car2); 13 }

and run our evaluation against them:

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