You are here: Basics Operations & Concepts > Querying > Native Queries

Native Queries

Wouldn't it be nice to write queries in the programming language that you are using? Wouldn't it be nice if all your query code was 100% typesafe, 100% compile-time checked and 100% refactorable? Wouldn't it be nice if the full power of object-orientation could be used by calling methods from within queries?

Native queries allow you do to this. They bring you a nice query interface which doesn't rely on string literals. Because native queries simply use the semantics of your programming language, they are perfectly standardized and a safe choice for the future.

Native Queries are available for all platforms supported by db4o.

Principle

Native Queries provide the ability to run one or more lines of code against all instances of a class. Native query expressions should return true to mark specific instances as part of the result set. db4o will attempt to optimize native query expressions where possible and use internal query processor to run them against indexes and without instantiating actual objects.

Dependencies

For a good native query performance you need to add these jars to your project:db4o-X.XX-nqopt-javax.jar, db4o-X.XX-instrumentation-javax.jar, bloat-1.0.jar. See "Dependency Overview"

Simple Example

Let's look at how a simple native query will look like. See also a collection of example queries.

ObjectSet<Pilot> result = container.query(new Predicate<Pilot>() {
    @Override
    public  boolean match(Pilot pilot) {
        return pilot.getName().equals("John");
    }
});
NativeQueryExamples.java: Check for equality of the name

Native Query Performance

There's one drawback of native queries: Under the hood db4o tries to analyze native queries to convert them to SODA. This is not possible for all queries. For some queries it is very difficult to analyze the flowgraph. In this case db4o will have to instantiate some of the persistent objects to actually run the native query code. db4o will try to analyze parts of native query expressions to keep object instantiation to the minimum.

The current state of the query optimization process is detailed in the chapter on Native Query Optimization