In our first installment, we configured Eclipse to use Jython and DB4O, and we wrote some simple code to create Pilot objects and store them.
In our second installment, we used Jython to retrieve the objects we save in the first part of the tutorial. Now, we need to update and delete these objects.
Then we will have learned how to perform the four basic functions of persistent storage: create, retrieve, update and delete – often referred to as CRUD
This tutorial is based on the Formula One DB4O tutorial.
Updating objects
Updating objects is just as easy as storing them. In fact, you use the same set() method to update your objects: just call set() again after modifying any object.
Java Code:
// updatePilot
ObjectSet result=db.get(new Pilot("Michael Schumacher",0));
Pilot found=(Pilot)result.next();
found.addPoints(11);
db.set(found);
System.out.println("Added 11 points for "+found);
retrieveAllPilots(db);
OUTPUT:
Added 11 points for Michael Schumacher/111
2
Michael Schumacher/111
Rubens Barrichello/99
Jython Code:
result=db.get(Pilot("Michael Schumacher",0))
found=result.next()
found.addPoints(11)
db.set(found)
print "Added 11 points for "+found
retrieveAllPilots(db)
Notice that we query for the object first. This is an important point. When you call set() to modify a stored object, if the object is not ‘known’ (having been previously stored or retrieved during the current session), db4o will insert a new object. db4o does this because it does not automatically match up objects to be stored, with objects previously stored. It assumes you are inserting a second object which happens to have the same field values.
To make sure you’ve updated the pilot, please return to any of the retrieval examples above and run them again.
Deleting objects
Objects are removed from the database using the delete() method.
Java Code:
// deleteFirstPilotByName
ObjectSet result=db.get(new Pilot("Michael Schumacher",0));
Pilot found=(Pilot)result.next();
db.delete(found);
System.out.println("Deleted "+found);
retrieveAllPilots(db);
Jython Code:
result=db.get(Pilot("Michael Schumacher",0))
found=result.next()
db.delete(found)
print "Deleted ", found
proto=Pilot(None,0)
result=db.get(proto)
listResult(result)
Let’s delete the other one, too.
result=db.get(Pilot("Rubens Barrichello",0))
found=result.next()
db.delete(found)
print "Deleted "+found
proto=Pilot(None,0)
result=db.get(proto)
listResult(result)
Please check the deletion with the retrieval examples above.
As with updating objects, the object to be deleted has to be ‘known’ to db4o. It is not sufficient to provide a prototype object with the same field values.
Next Installment:
In our next installment, we will provide the full source code for this tutorial. We will also reflect on the differences between the Jython code and the Java code.