get(proto);
if (result.hasNext()) return (Celebrity)result.next();
return null;
}
First of all, we need to create a prototype object of the same type as the object, or
objects we are going to retrieve:
Celebrity proto = new Celebrity();
Next, we need to set some of the properties of the prototype to the values we want
to see in the returned objects. The database will return all the objects that match all
non-default values of the prototype's properties. In our example we want to find
a celebrity with a certain ID, so we set the ID property of the prototype to the
desired value:
proto.setId(id);
Then we pass the prototype to the get method, and the result will be provided as
an ObjectSet:
ObjectSet result = db.get(proto);
We can then check whether there is something in the result by using the hasNext
method and retrieving that next object as the example shows.
Storing an object in the database is also quite simple. This is how addCelebrity
method looks:
public void addCelebrity(Celebrity c)
{
db.set(c);
}
Creating a Real Data Source with db4o
[ 254 ]
However, there is one potential problem with such an implementation. Say we have
just saved a Celebrity object containing the data for Bill Clinton.
Pages:
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311