01: package com.db4o.f1.chapter1;
02:
03: import java.io.File;
04:
05: import com.db4o.Db4o;
06: import com.db4o.ObjectContainer;
07: import com.db4o.ObjectSet;
08: import com.db4o.f1.Util;
09:
10: public class FirstStepsExample extends Util {
11: public static void main(String[] args) {
12: new File(Util.DB4OFILENAME).delete();
13: accessDb4o();
14: new File(Util.DB4OFILENAME).delete();
15: ObjectContainer db = Db4o.openFile(Util.DB4OFILENAME);
16: try {
17: storeFirstPilot(db);
18: storeSecondPilot(db);
19: retrieveAllPilots(db);
20: retrievePilotByName(db);
21: retrievePilotByExactPoints(db);
22: updatePilot(db);
23: deleteFirstPilotByName(db);
24: deleteSecondPilotByName(db);
25: } finally {
26: db.close();
27: }
28: }
29:
30: public static void accessDb4o() {
31: ObjectContainer db = Db4o.openFile(Util.DB4OFILENAME);
32: try {
33: // do something with db4o
34: } finally {
35: db.close();
36: }
37: }
38:
39: public static void storeFirstPilot(ObjectContainer db) {
40: Pilot pilot1 = new Pilot("Michael Schumacher", 100);
41: db.set(pilot1);
42: System.out.println("Stored " + pilot1);
43: }
44:
45: public static void storeSecondPilot(ObjectContainer db) {
46: Pilot pilot2 = new Pilot("Rubens Barrichello", 99);
47: db.set(pilot2);
48: System.out.println("Stored " + pilot2);
49: }
50:
51: public static void retrieveAllPilotQBE(ObjectContainer db) {
52: Pilot proto = new Pilot(null, 0);
53: ObjectSet result = db.get(proto);
54: listResult(result);
55: }
56:
57: public static void retrieveAllPilots(ObjectContainer db) {
58: ObjectSet result = db.get(Pilot.class);
59: listResult(result);
60: }
61:
62: public static void retrievePilotByName(ObjectContainer db) {
63: Pilot proto = new Pilot("Michael Schumacher", 0);
64: ObjectSet result = db.get(proto);
65: listResult(result);
66: }
67:
68: public static void retrievePilotByExactPoints(ObjectContainer db) {
69: Pilot proto = new Pilot(null, 100);
70: ObjectSet result = db.get(proto);
71: listResult(result);
72: }
73:
74: public static void updatePilot(ObjectContainer db) {
75: ObjectSet result = db.get(new Pilot("Michael Schumacher", 0));
76: Pilot found = (Pilot) result.next();
77: found.addPoints(11);
78: db.set(found);
79: System.out.println("Added 11 points for " + found);
80: retrieveAllPilots(db);
81: }
82:
83: public static void deleteFirstPilotByName(ObjectContainer db) {
84: ObjectSet result = db.get(new Pilot("Michael Schumacher", 0));
85: Pilot found = (Pilot) result.next();
86: db.delete(found);
87: System.out.println("Deleted " + found);
88: retrieveAllPilots(db);
89: }
90:
91: public static void deleteSecondPilotByName(ObjectContainer db) {
92: ObjectSet result = db.get(new Pilot("Rubens Barrichello", 0));
93: Pilot found = (Pilot) result.next();
94: db.delete(found);
95: System.out.println("Deleted " + found);
96: retrieveAllPilots(db);
97: }
98: }
|