Simple Object Persistence with the db4o Object Database
Pages: 1, 2
Storing the data
A Team object can be stored with a single line of code:
db.set(t1);
where db is a reference to an ObjectContainer object, which was created
by opening a new database file, like this:
ObjectContainer db = Db4o.openFile(filename);
A db4o database is a single file with a .yap
extension, and its set method
is used to store objects.
Note that this line stores the Team object and its collection of Player objects.
We can test this by retrieving one of those Player objects. The simplest way
to do this is by using QBE.
Simple querying: QBE
The following code lists all Player objects that
match an example object; there should only be one here. Results
are retrieved as an ObjectSet by
calling the get method
of the ObjectContainer.
Player examplePlayer = new Player("Barry Bonds",0,0f);
ObjectSet result=db.get(examplePlayer);
System.out.println(result.size());
while(result.hasNext()) {
System.out.println(result.next());
}
We can get all the Player objects that have been stored
by creating a dummy example object (all fields are null or 0),
as follows:
Player examplePlayer = new Player(null,0,0f);
ObjectSet result=db.get(examplePlayer);
System.out.println(result.size());
while(result.hasNext()) {
System.out.println(result.next());
}
The output looks like this:
8
Kazuhisa Ishii:0.127, 13
Shawn Green:0.266
Cesar Izturis:0.288
Adrian Beltre:0.334
Kirk Rueter:0.131, 9
Ray Durham:0.282
Marquis Grissom:0.279
Barry Bonds:0.362
Note that we can retrieve all objects of the Player class and
its subclasses (just
Pitcher in this example) without any extra effort. The Pitcher
objects show up in the output as they have the extra wins attribute
listed. With a relational database we
would have had to decide how to map the inheritance tree to tables and possibly
have had to join tables to retrieve all the attributes of all the objects.
Updating and deleting
Updating objects can be achieved using a combination of the above techniques.
The following code assumes that only one match is found, and the matching object
is cast to Player so that its attributes can be modified.
Player examplePlayer = new Player("Shawn Green",0,0f);
ObjectSet result = db.get(examplePlayer);
Player p = (Player) result.next();
p.setBattingAverage(0.299f);
db.set(p);
Objects can be deleted from the database in a similar way:
Player examplePlayer = new Player("Ray Durham",0,0f);
ObjectSet result = db.get(examplePlayer);
Player p = (Player) result.next();
db.delete(p);
More powerful query support
One of the major drawbacks of early versions of db4o was that QBE provides
fairly limited querying capability. For example, you couldn't run a query
like "all players
with batting average greater than .300". db4o now includes the S.O.D.A.
API to provide querying that comes much closer to the power of SQL. An instance
of the Query class represents a node in
a query criteria graph to which constraints can be applied. A node can represent
a class, multiple classes, or a class attribute.
The following code demonstrates how to do the query described in the previous
paragraph. We define a query graph node and constrain it to the
Player class. This means that the query will only return Player objects.
We then descend the graph to find a node representing an attribute named “battingAverage” and
constrain this to be greater than 0.3. Finally, the query is executed to return
all objects in the database that match the constraints.
Query q = db.query();
q.constrain(Player.class);
q.descend("battingAverage").constrain(new Float(0.3f)).greater();
ObjectSet result = q.execute();
At first glance, this performs a similar query to an SQL query, like this:
SELECT * FROM players WHERE battingAverage > 0.3
However, the design of the Player class allows inverse relationships
to be created between Team and Player objects, as
shown in the test data. A Team has a reference to a list of Player objects,
while each
Player has a reference to a Team. This means that
the result of this query contains Player and Team objects. The
code below demonstrates this:
System.out.println(result.size());
while(result.hasNext()) {
// Print Player
Player p = (Player) result.next();
System.out.println(p);
// Getting Player also gets Team - print Team
Team t = p.getTeam();
System.out.println(t);
}
Output:
2
Adrian Beltre:0.334
Dodgers
Barry Bonds:0.362
Giants
The query is now similar to an SQL query, like this:
SELECT teams.name, players.name, players.battingAverage FROM teams, players
WHERE teams.teamID = players.playerID
AND battingAverage > 0.3
This worked because the inverse relationship was designed into the object
model. Object databases are navigational: you can only retrieve data
following the direction of predefined relationships. Relational databases,
on the other hand, have no directionality in their table joins and therefore allow
more flexibility for ad-hoc queries. However, given the right object relationships,
related objects can be retrieved from the object database with very little
programming effort. The database model and the application object model are
identical, so there is no need for the programmer to think differently about
the data. If you can get the Team for
a given Player
when the objects are in memory, you can do the same from the database.
What else can S.O.D.A. do?
SQL allows results to be sorted in order; S.O.D.A. does too. This example
shows how the stored Player objects can be retrieved in order
of battingAverage. (It's pretty obvious which ones are the pitchers now!)
Query q = db.query();
q.constrain(Player.class);
q.descend("battingAverage").orderAscending();
ObjectSet result = q.execute();
Output:
7
Kazuhisa Ishii:0.127, 13
Kirk Rueter:0.131, 9
Marquis Grissom:0.279
Cesar Izturis:0.288
Shawn Green:0.299
Adrian Beltre:0.334
Barry Bonds:0.362
S.O.D.A. allows more complex queries to be defined using code that is quite simple once you get past the temptation to think the relational way. To set constraints you just navigate around the query graph to find the classes or attributes you want to put conditions on. The query graph is closely related to the domain object model, which should (hopefully) be well understood by the developer. On the other hand, to achieve a similar result with SQL you need to take account of how the domain objects have been mapped to relational tables.
This example shows how to set conditions on two attributes of the Player
class to find players with batting average above .130
who are also pitchers with more than 5 wins. Again, we define a query graph
node and constrain it to the
Player class. We then descend the graph to find a node representing
the attribute named “battingAverage” and
constrain this to be greater than 0.13. The result of this is a Constraint object.
To set the next constraint, we descend to find the node representing the attribute "wins";
this in itself means that the query will only find Pitcher objects.
This node is constrained to be greater than 5, and this is combined using a
logical "AND" with the first Constraint object.
Query q = db.query();
q.constrain(Player.class);
Constraint constr =
q.descend("battingAverage").constrain(
new Float(0.13f)).greater();
q.descend("wins").constrain(
new Integer(5)).greater().and(constr);
result = q.execute();
Output:
1
Kirk Rueter:0.131, 9
Giants
The last example shows how to combine conditions on attributes of different
classes to find players with batting average above .300
who are in teams with more than 92 wins. The easiest way to do this is
to start with Player, and then
navigate to Team. We descend to
find the "battingAverage" node as before and set a Constraint.
We then descend to find the "team" attribute. As this attribute is of type Team,
the node represents the Team class, so we can descend again to
the node representing the "won" attribute of Team and
set a constraint on that. Finally, we combine this with the first
Constraint.
Query q = db.query();
q.constrain(Player.class);
Constraint constr =
q.descend("battingAverage").constrain(
new Float(0.3f)).greater();
q.descend("team").descend("won").constrain(
new Integer(92)).smaller().and(constr);
result = q.execute();
Output:
1
Barry Bonds:0.362
Giants
Conclusion
A small footprint, embeddable object database offers a very simple, compact route to object persistence. db4o is now an open source object database that offers a range of attractive features and supports both Java and .NET. The simplicity of installation and use as well as the lack of an impedance mismatch between object and data models make db4o very useful in a range of business and educational applications.
Resources
- Source code for this article
- Download the db4o database
Jim Paterson is a Lecturer at Glasgow Caledonian University in the UK , specializing in web development and object-oriented software development.
Return to ONJava.com