Thursday, March 29, 2007

db4o Java Bean Database

The db4o http://www.db4o.com/ project makes a very simple, light-weight object database. It's free, too. Maybe too free, as they use GPL. But see comment below. Obviously this sort of thing is great if you do a lot of POJO development (say, with JSF) and need some persistent storage.

The downloadable documentation is pretty good, as is this article: http://www-128.ibm.com/developerworks/java/library/j-db4o1.html

Two issues with the docs. First, their examples always assume that your bean has a complete constructor that sets all fields. You may not wish to do this, so instead you can just use the appropriate set method instead.

Assume you have a MyBean class with the fields beanName, beanCreationDate, beanCreator, and so on. Then:

MyBean myBean=new MyBean();
myBean.setBeanName("Junk");
ObjectSet results=db.get(myBean);

The returned results set will have all the MyBean instances that you have stored with the name "Junk".

Second, you can only delete specific bean instances. That is, the corresponding db.delete(myBean) method for the above code will not delete all the matching beans.

//Won't work if your bean has multiple fields.
MyBean myBean=new MyBean();
myBean.setBeanName("Junk");
//Won't work
db.delete(myBean);

To do this, you have to get the specific beans that you matched in the get() and the delete them one by one. For example,

MyBean myBean=new MyBean();
myBean.setBeanName("Junk");
ObjectSet results=db.get(myBean);
//Reassign the myBean.
while(results.hasNext());
myBean=(MyBean)results.next();
db.delete(myBean);
}

1 comment:

Christof Wittig said...

> Maybe too free, as they use GPL.
We're dual licensed like MySQL and can always provide a conventional, commercial license, if you're uncomfortable with the terms of the GPL.
In addition, we also offer the db4o Opensource Compatibility license (dOCL) for free use of db4o together with other opensource projects under non-GPL licenses such as BSD, EPL, LGPL, etc.
Have fun with db4o and share your feedback!
Cheers,
Christof