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

Advantages of NQ sorting:

  • type-safe queries and sorting, compile-time checking;
  • ability to implement any custom sorting algorithm

The main disadvantage is decreased performance.