Monday, March 17, 2008

DB4O introduction

Db4o is a high-performance object database for Java and .NET.

Ø         Open db

     ObjectContainer db = Db4o.openFile(filename);

 

Ø         Insert

Objects are inserted by using set() method.

ClassName obj = new ClassName(parameters);

db.set(obj);

 

Ø         Retrieve

(1)    Query by Example (QBE)

       Create a prototypical object for db4o to use as an example of what you wish to retrieve. Db4o will return all of the objects which match all non-default field values. The results will be returned as an ObjectSet instance.

ClassName obj = new ClassName(values…); //prototypical object

ObjectSet result = db.get( obj );

listResult( result );

Db4o supplies a shortcut to retrieve all instances of a class:

ObjectSet result = db.get(ClassName.class);

Following code can be used to iterate over the results:

while( result.hasNext() ){

    System.out.println( result.next() );

}

(2)    Native Query(NQ) --- main db4o querying interface.

       Native Queries provide the ability to run one or more lines of code against all instances of a class. Native query expressions return true to mark specific instances as part of the result set.

    List<ClassName> objs = db.query( new Predicate<ClassName>() {

           public Boolean match(ClassName obj){

                  return obj.getProperty() == value;

           }

    }

       Users must be very careful with side effects --- especially those that might affect persistent objects.

(3)    SODA Query API

 

Ø         Update

       Updating objects is as easy as storing them. You use the same set() method to update objects: just call set() again modifying any object.

ObjectSet result = db.get(new ClassName(parameters));

ClassName found = (ClassName)result.next();

found.methodName(parameters);

db.set(found);

Note: we query the object first. If the object is not ‘known’ (having been previously stored or retrieved during the current session), db4o will insert a new object instead of updating existing object. In this case, db4o think that you want to insert a new object which has the same field values.

 

Ø         Delete

       Objects are removed by using delete() method.

ObjectSet result = db.get( new ClassName(…));

ClassName found = (ClassName)result.next();

db.delete( found );

If you want to tune DB4O to get higher performance, you need to change the default configuration.

No comments: