1 package com.db4odoc.f1.queries; 2 3 import java.util.List ; 4 5 import com.db4o.Db4o; 6 import com.db4o.ObjectContainer; 7 import com.db4o.ObjectSet; 8 import com.db4o.query.Predicate; 9 import com.db4o.query.Query; 10 11 public class NQExample { 12 public final static String YAPFILENAME="formula1.yap"; 13 14 public static void main(String [] args) { 15 ObjectContainer db=Db4o.openFile(YAPFILENAME); 16 try { 17 storePilots(db); 18 retrieveComplexSODA(db); 19 retrieveComplexNQ(db); 20 retrieveArbitraryCodeNQ(db); 21 clearDatabase(db); 22 } 23 finally { 24 db.close(); 25 } 26 } 27 29 public static void primitiveQuery(ObjectContainer db){ 30 List <Pilot> pilots = db.query(new Predicate<Pilot>() { 31 public boolean match(Pilot pilot) { 32 return pilot.getPoints() == 100; 33 } 34 }); 35 } 36 38 39 public static void advancedQuery(ObjectContainer db){ 40 List <Pilot> result = db.query(new Predicate<Pilot>() { 41 public boolean match(Pilot pilot) { 42 return pilot.getPoints() > 99 43 && pilot.getPoints() < 199 44 || pilot.getName().equals("Rubens Barrichello"); 45 } 46 }); 47 } 48 50 public static void storePilots(ObjectContainer db) { 51 db.set(new Pilot("Michael Schumacher",100)); 52 db.set(new Pilot("Rubens Barrichello",99)); 53 } 54 56 public static void retrieveComplexSODA(ObjectContainer db) { 57 Query query=db.query(); 58 query.constrain(Pilot.class); 59 Query pointQuery=query.descend("points"); 60 query.descend("name").constrain("Rubens Barrichello") 61 .or(pointQuery.constrain(new Integer (99)).greater() 62 .and(pointQuery.constrain(new Integer (199)).smaller())); 63 ObjectSet result=query.execute(); 64 listResult(result); 65 } 66 68 public static void retrieveComplexNQ(ObjectContainer db) { 69 ObjectSet result=db.query(new Predicate<Pilot>() { 70 public boolean match(Pilot pilot) { 71 return pilot.getPoints()>99 72 && pilot.getPoints()<199 73 || pilot.getName().equals("Rubens Barrichello"); 74 } 75 }); 76 listResult(result); 77 } 78 80 public static void retrieveArbitraryCodeNQ(ObjectContainer db) { 81 final int[] points={1,100}; 82 ObjectSet result=db.query(new Predicate<Pilot>() { 83 public boolean match(Pilot pilot) { 84 for(int i=0;i<points.length;i++) { 85 if(pilot.getPoints()==points[i]) { 86 return true; 87 } 88 } 89 return pilot.getName().startsWith("Rubens"); 90 } 91 }); 92 listResult(result); 93 } 94 96 public static void clearDatabase(ObjectContainer db) { 97 ObjectSet result=db.get(Pilot.class); 98 while(result.hasNext()) { 99 db.delete(result.next()); 100 } 101 } 102 104 public static void listResult(ObjectSet result) { 105 System.out.println(result.size()); 106 while(result.hasNext()) { 107 System.out.println(result.next()); 108 } 109 } 110 } 112 | Popular Tags |