2

I am using db4o and was wondering, how can I get the total number of objects in the database? There isn't an explicit way using the API; however, I can write a query to simply count all the objects, but I was hoping for a more direct way to do it.

Walter

Walter
  • 1,290
  • 2
  • 21
  • 46
  • Records? I thought db4o was an object database? How do you define a record? It's not relational. – duffymo Mar 26 '11 at 02:26

1 Answers1

4

There are two ways:

The first one is to query for the type-object and then get the count:

  int numberOfObjects = container.query(Object.class).size();

However this is probably slow, because the query will construct a result list of all objects. And in a large database that can take time.

The second one is to read the meta data of all stored classes and sum up the count. This is certainly a lot faster:

    int numberOfObjects = 0;
    for(StoredClass storedClass : container.ext().storedClasses()){
        // Filter out db4o internal objects
        // and filter out object which have a parent-class, because these are in the count of the parent
        if(!storedClass.getName().startsWith("com.db4o") &&
                null==storedClass.getParentStoredClass()) {
            numberOfObjects += storedClass.instanceCount();
        }
    }
    System.out.println("Number of objects stored "+numberOfObjects);

Note here that it also report db4o internal classes. So I filter them out.

Gamlor
  • 12,978
  • 7
  • 43
  • 70
  • 1
    With this code, if you have an inheritance hierarchy of two classes, you will get the instanceCount multiple times for each class in the hierarchy. If you add an additional check and only add the instanceCount of classes that don't have a parent class, then you should be fine. – Carl Rosenberger Mar 26 '11 at 13:58
  • Cool, that was exactly what I was thinking. That probably is about as elegant as it can get without having this functionality released from db4o. – Walter Mar 27 '11 at 14:08