You are here: Best Practices > Paging

Paging

Currently db4o doesn't provide any paging mechanism at all. However all db4o query results are lazy loaded. db4o returns a result list which only contains the ids of the objects and will load the object as soon as you access it. This means you can page by only accessing the indexes of the range you're interested in.

Since the result sets of db4o implement the Java List interface it has the sub list method. With this method you easily get only a sub set of the result. Or you can build your own paging-method based on the sub list method on the lists.

public  static <T> List<T> paging(List<T> listToPage, int limit){
    return paging(listToPage,0,limit);
}

public  static <T> List<T> paging(List<T> listToPage, int start, int limit){
    if(start>listToPage.size()){
        throw  new IllegalArgumentException("You cannot start the paging outside the list." +
                " List-size: "+listToPage.size()+" start: "+start);
    }
    int end = calculateEnd(listToPage, start, limit);
    return listToPage.subList(start, end);

}

private  static <T> int calculateEnd(List<T> resultList, int start, int limit) {
    int end = start + limit;
    if(end>=resultList.size()){
        return resultList.size();
    }
    return end;
}
PagingUtility.java: Paging utility methods

And then of course you can use the utility methods on the result-sets of db4o.

final ObjectSet<StoredItems> queryResult = container.query(StoredItems.class);
List<StoredItems> pagedResult = PagingUtility.paging(queryResult, 2, 2);
TestPagingUtility.java: Use the paging utility