|
2. First Steps
Let's get started as simple as possible. We are going to demonstrate how to store, retrieve, update and delete instances of a single class that only contains primitive and String members. In our example this will be a Formula One (F1) pilot whose attributes are his name and the F1 points he has already gained this season.
First we create a class to hold our data. It looks like this:
Namespace com.db4o.f1.chapter1
Public Class Pilot
Private _name As String
Private _points As Integer
Public Sub New(ByVal name As String, ByVal points As Integer)
_name = name
_points = points
End Sub
Public ReadOnly Property Name() As String
Get
Return _name
End Get
End Property
Public ReadOnly Property Points() As Integer
Get
Return _points
End Get
End Property
Public Sub AddPoints(ByVal points As Integer)
_points += points
End Sub
Public Overloads Overrides Function ToString() As String
Return String.Format("{0}/{1}", _name, _points)
End Function
End Class
End Namespace
|
Notice that this class does not contain any db4o-related code.
2.1. Opening the database
To access a db4o database file or create a new one, call Db4o.openFile(), providing the path to your file as the parameter, to obtain an ObjectContainer instance. ObjectContainer represents "The Database", and will be your primary interface to db4o. Closing the container with the #.close() method will close the database file and release all resources associated with it.
[accessDb4o]
Dim db As ObjectContainer = Db4oFactory.OpenFile(Util.YapFileName)
Try
' do something with db4o
Finally
db.Close()
End Try |
For the following examples we will assume that our environment takes care of opening and closing the ObjectContainer automagically, and stores the reference in a variable named 'db'.
2.2. Storing objects
To store an object, we simply call set() on our database, passing any object as a parameter.
[storeFirstPilot]
Dim pilot1 As Pilot = New Pilot("Michael Schumacher", 100)
db.Set(pilot1)
Console.WriteLine("Stored {0}", pilot1) |
OUTPUT: Stored Michael Schumacher/100
|
|
We'll need a second pilot, too.
[storeSecondPilot]
Dim pilot2 As Pilot = New Pilot("Rubens Barrichello", 99)
db.[Set](pilot2)
Console.WriteLine("Stored {0}", pilot2) |
OUTPUT: Stored Rubens Barrichello/99
|
2.3. 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 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 results:
Public Shared Sub ListResult(ByVal result As ObjectSet)
Console.WriteLine(result.Count)
For Each item As Object In result
Console.WriteLine(item)
Next
End Sub |
To retrieve all pilots from our database, we provide an 'empty' prototype:
[retrieveAllPilotQBE]
Dim proto As Pilot = New Pilot(Nothing, 0)
Dim result As ObjectSet = db.[Get](proto)
ListResult(result) |
OUTPUT: 2
Rubens Barrichello/99
Michael Schumacher/100
|
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.
db4o also supplies a shortcut to retrieve all instances of a class:
[retrieveAllPilots]
Dim result As ObjectSet = db.[Get](GetType(Pilot))
ListResult(result) |
OUTPUT: 2
Rubens Barrichello/99
Michael Schumacher/100
|
For .NET 2.0 there also is a generics shortcut, using the query method:
IList <Pilot> pilots = db.query<Pilot>(typeof(Pilot)); |
To query for a pilot by name:
[retrievePilotByName]
Dim proto As Pilot = New Pilot("Michael Schumacher", 0)
Dim result As ObjectSet = db.[Get](proto)
ListResult(result) |
OUTPUT: 1
Michael Schumacher/100
|
And to query for Pilots with a specific number of points:
[retrievePilotByExactPoints]
Dim proto As Pilot = New Pilot(Nothing, 100)
Dim result As ObjectSet = db.[Get](proto)
ListResult(result) |
OUTPUT: 1
Michael Schumacher/100
|
Of course there's much more to db4o queries. They will be covered in more depth in later chapters.
2.4. 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.
[updatePilot]
Dim result As ObjectSet = db.[Get](New Pilot("Michael Schumacher", 0))
Dim found As Pilot = DirectCast(result.[Next](), Pilot)
found.AddPoints(11)
db.[Set](found)
Console.WriteLine("Added 11 points for {0}", found)
RetrieveAllPilots(db) |
OUTPUT: Added 11 points for Michael Schumacher/111
2
Rubens Barrichello/99
Michael Schumacher/111
|
Notice that we query for the object first. This is an importaint 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.
2.5. Deleting objects
Objects are removed from the database using the delete() method.
[deleteFirstPilotByName]
Dim result As ObjectSet = db.[Get](New Pilot("Michael Schumacher", 0))
Dim found As Pilot = DirectCast(result.[Next](), Pilot)
db.Delete(found)
Console.WriteLine("Deleted {0}", found)
RetrieveAllPilots(db) |
OUTPUT: Deleted Michael Schumacher/111
1
Rubens Barrichello/99
|
Let's delete the other one, too.
[deleteSecondPilotByName]
Dim result As ObjectSet = db.[Get](New Pilot("Rubens Barrichello", 0))
Dim found As Pilot = DirectCast(result.[Next](), Pilot)
db.Delete(found)
Console.WriteLine("Deleted {0}", found)
RetrieveAllPilots(db) |
OUTPUT: Deleted Rubens Barrichello/99
0
|
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.
2.6. Conclusion
That was easy, wasn't it? We have stored, retrieved, updated and deleted objects with a few lines of code. But what about complex queries? Let's have a look at the restrictions of QBE and alternative approaches in the
next chapter .
2.7. Full source
Imports System
Imports System.IO
Imports com.db4o
Namespace com.db4o.f1.chapter1
Public Class FirstStepsExample
Inherits Util
Public Shared Sub Main(ByVal args As String())
File.Delete(Util.YapFileName)
AccessDb4o()
File.Delete(Util.YapFileName)
Dim db As ObjectContainer = Db4oFactory.OpenFile(Util.YapFileName)
Try
StoreFirstPilot(db)
StoreSecondPilot(db)
RetrieveAllPilots(db)
RetrievePilotByName(db)
RetrievePilotByExactPoints(db)
UpdatePilot(db)
DeleteFirstPilotByName(db)
DeleteSecondPilotByName(db)
Finally
db.Close()
End Try
End Sub
Public Shared Sub AccessDb4o()
Dim db As ObjectContainer = Db4oFactory.OpenFile(Util.YapFileName)
Try
' do something with db4o
Finally
db.Close()
End Try
End Sub
Public Shared Sub StoreFirstPilot(ByVal db As ObjectContainer)
Dim pilot1 As Pilot = New Pilot("Michael Schumacher", 100)
db.Set(pilot1)
Console.WriteLine("Stored {0}", pilot1)
End Sub
Public Shared Sub StoreSecondPilot(ByVal db As ObjectContainer)
Dim pilot2 As Pilot = New Pilot("Rubens Barrichello", 99)
db.[Set](pilot2)
Console.WriteLine("Stored {0}", pilot2)
End Sub
Public Shared Sub RetrieveAllPilotQBE(ByVal db As ObjectContainer)
Dim proto As Pilot = New Pilot(Nothing, 0)
Dim result As ObjectSet = db.[Get](proto)
ListResult(result)
End Sub
Public Shared Sub RetrieveAllPilots(ByVal db As ObjectContainer)
Dim result As ObjectSet = db.[Get](GetType(Pilot))
ListResult(result)
End Sub
Public Shared Sub RetrievePilotByName(ByVal db As ObjectContainer)
Dim proto As Pilot = New Pilot("Michael Schumacher", 0)
Dim result As ObjectSet = db.[Get](proto)
ListResult(result)
End Sub
Public Shared Sub RetrievePilotByExactPoints(ByVal db As ObjectContainer)
Dim proto As Pilot = New Pilot(Nothing, 100)
Dim result As ObjectSet = db.[Get](proto)
ListResult(result)
End Sub
Public Shared Sub UpdatePilot(ByVal db As ObjectContainer)
Dim result As ObjectSet = db.[Get](New Pilot("Michael Schumacher", 0))
Dim found As Pilot = DirectCast(result.[Next](), Pilot)
found.AddPoints(11)
db.[Set](found)
Console.WriteLine("Added 11 points for {0}", found)
RetrieveAllPilots(db)
End Sub
Public Shared Sub DeleteFirstPilotByName(ByVal db As ObjectContainer)
Dim result As ObjectSet = db.[Get](New Pilot("Michael Schumacher", 0))
Dim found As Pilot = DirectCast(result.[Next](), Pilot)
db.Delete(found)
Console.WriteLine("Deleted {0}", found)
RetrieveAllPilots(db)
End Sub
Public Shared Sub DeleteSecondPilotByName(ByVal db As ObjectContainer)
Dim result As ObjectSet = db.[Get](New Pilot("Rubens Barrichello", 0))
Dim found As Pilot = DirectCast(result.[Next](), Pilot)
db.Delete(found)
Console.WriteLine("Deleted {0}", found)
RetrieveAllPilots(db)
End Sub
End Class
End Namespace
|
--
generated by Doctor courtesy of db4objects Inc.