I am using db4o and was wondering, how can I g开发者_StackOverflow社区et 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
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.
精彩评论