Native Query Sorting

Native Query syntax allows you to specify a comparator, which will be used to sort the results:

Java:

<TargetType> ObjectSet<TargetType> query(Predicate<TargetType> predicate,                                      QueryComparator<TargetType> comparator)

In order to get the same results as in SODA Sorting example we will write the following code:

SortingExample.java: getObjectsNQ
01public static void getObjectsNQ() { 02 ObjectContainer container = Db4o.openFile(DB4O_FILE_NAME); 03 try { 04 long t1 = System.currentTimeMillis(); 05 ObjectSet result = container.query( 06 new Predicate<Pilot>() { 07 public boolean match(Pilot pilot) { 08 return true; 09 } 10 }, new QueryComparator<Pilot>() { 11 public int compare(Pilot p1, Pilot p2) { 12 int result = p1.getPoints() 13 - p2.getPoints(); 14 if (result == 0) { 15 return p1.getName().compareTo( 16 p2.getName()); 17 } else { 18 return -result; 19 } 20 } 21 }); 22 long t2 = System.currentTimeMillis(); 23 long diff = t2 - t1; 24 System.out 25 .println("Time to execute with NQ and comparator: " 26 + diff + " ms."); 27 listResult(result); 28 } finally { 29 container.close(); 30 } 31 }

Advantages of NQ sorting:

The main disadvantage is decreased performance as at current stage optimization of sorted Native Queries is not possible.