Native Query
Written by JODB Master   
Thursday, 15 November 2007

Concept and Principle

The concept of native queries is taken from the following two papers:

- Cook/Rosenberger, Native Queries for Persistent Objects, A Design White Paper

- Cook/Rai, Safe Query Objects: Statically Typed Objects as Remotely Executable Queries

Native Queries provide the ability to run an arbitrary of code against all instances of the specified class. Native query expressions should return true to mark specific instances as part of the result set. JODB database will optimize/transform native query expressions and run them against indexes and without instantiating actual objects, where this is possible.

Simple Example
Predicate<Pilot> predicate= new Predicate<Pilot>() {
       public boolean match(Pilot pilot) {
             return pilot.getPoints() > 100 && pilot.getPoints() < 500 ;
 List<Pilot> pilots = sessionContainer.query(predicate);

The resulting set will represent all instances of Predicate object with 'points' value greater than 100 and less than 500.

One of the obvious benefits of Native Queries is the seamless autocompletion and code refactoring functionality available in most modern IDE's (i.e. Eclipse).


Complex Queries and Performance

In general you can run any code as native queries but be aware of performance penalties for complicated code. As it was mentioned before the JODB will try to optimize queries and avoid excessive object instantiation. For complex queries this process could be overcomplicated and force JODB to instantiate actual instances.
To programmatically verify if an arbitrary predicate code can be run optimized you can use the JODBSessionContainer.isOptimizedQuery(..) method. The method especially usable if you want to safeguard your code against none optimizable queries (i.e. by throwing an Exception).

Required 3rd Party Libraries

 The process of query analysis and optimization involves ASM project hosted by ObjectWeb. In order to run native queries you'll have to add ASM libraries (included within distribution as '3rdpartylibs') to your classpath.