Search code examples
c#db4o

db4o best practice to query objects from db


I am using two different ways to query objects in db4o and I would like to discuss about it.

1) In this first example, I create an instance of ObjectContainer, I open the connection, and then I close it.

ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), "User");
ObjectSet result = db.queryByExample(user);
db.close();

2) In this second example, I create an ObjectServer and let the connection open for the whole lifecycle of the application. I also open ObjectContainer from the ObjectServer, make my query and then close it:

ObjectServer userDb = Db4oClientServer.openServer(Db4oClientServer.newServerConfiguration(), "User", 0);
ObjectContainer client = client = userDb.openClient();
ObjectSet result = client.queryByExample(user);
client.close();

--

What are the main difference between both methods? Is it dangerous if I never close the ObjectServer?

In my opinion, the second method is better, because if two different instances call the method showed in the first example, the second caller will get an exception, cause the database would be locked, but in the second example I do not have such a problem. As I do not have much experience with db4o I prefer to ask if I am on the right way.


Solution

  • db4o works best when you keep the connection open for the whole application life cycle.

    If you retrieve an object, close the database, reopen it and store the object again db4o will not realize that the object is already stored (since you closed the connection and whence db4o's reference system also) and will store a second instance.

    Another issue (if you run db4o in embedded mode) is that opening the database is a time consuming operation, so, if you keep opening/close the database the certainly will have performance issues (by the other hand, opening client connections is not so costly and so should pose no problem at all).