In Our last installment, we configured Eclipse to use Jython and DB4O, and we wrote some simple code to create Pilot objects and store them. In this installment, we are going to retrieve those objects.
This tutorial is based on the Formula One DB4O tutorial.
Retrieving objects
db4o supplies three different quering systems, Query by Example (QBE), Native Queries (NQ) and the SODA Query API (SODA). In this first example we will introduce QBE. Once you are familiar with storing objects, we encourage you to use Native Queries, the main db4o querying interface. When using Jython, this may present some challenges – more on that later.
When using Query-By-Example, you create a prototypical object for db4o to use as an example of what you wish to retrieve. db4o will retrieve all objects of the given type that contain the same (non- default) field values as the example. The results will be returned as an ObjectSet instance. We will use a convenience method #listResult() to display the contents of our result ObjectSet :
Java Code:
public static void listResult (ObjectSet result){
System.out.println(result.size());
while(result.hasNext()) {
System.out.println(result.next());
}
}
Jython Equivilant:
def listResult (result):
print result.size()
while result.hasNext():
print result.next()
To retrieve all pilots from our database, we provide an ‘empty’ prototype:
Java Code:
// retrieveAllPilotQBE Pilot proto=new Pilot(null,0); ObjectSet result=db.get(proto); listResult(result);
Jython Equivilant:
proto=Pilot(None,0)
result=db.get(proto)
listResult(result)
The output is:
2
Michael Schumacher/100
Rubens Barrichello/99
Note that we specify 0 points, but our results were not constrained to only those Pilots with 0 points; 0 is the default value for int fields. Also note that where we employ null in Java, we use None in Jython.
db4o also supplies a shortcut to retrieve all instances of a class:
Java Code:
ObjectSet result=db.get(Pilot.class); listResult(result);
Jython Equivilant:
result=db.get(Pilot) listResult(result)
Jython vs Java:
You will notice that the Jython is nicer to read and write. (I think so, at any rate.) Functions return objects that are typed, but we do not have to declare the type in the code. Some people make a fuss about type safety in Java, C# and other languages. My own opinion is that while type declarations do help the compiler, most of the time they do not help the programmer. Type declarations are more work than I want to do most of the time – developer productivity is what I want.
(Note: Because my clients these days tend to be departments of the Canadian government, I am unlikely to have a chance to use Python or Jython in the near future for anything but my own interest. However, one must always be prepared to offer alternatives, and one must always be willing to advocate. )
In our next installment, we will look at updating and deleting DB4O objects. After that, perhaps we can start to think about the Active Record pattern.