The object container is the door to the database access. It's the starting point for all database operations.
The object container is the interface for accessing the database. To open the database you pass the file-name to the object container factory. Normally you should open an object container when the application starts and close it when it is shuts down.
ObjectContainer container = Db4oEmbedded.openFile("databaseFile.db4o"); try { // use the object container } finally { container.close(); }
Storing a object with db4o is extremely easy. Open the object container and pass your object to the store method and db4o will do the rest. There's no mapping required. db4o will read the class meta data, the read the object values with reflection and store the data.
ObjectContainer container = Db4oEmbedded.openFile("databaseFile.db4o"); try { Pilot pilot = new Pilot("Joe"); container.store(pilot); } finally { container.close(); }
Querying for objects is also easy. There are different query interfaces available with different benefits. See "Querying"
The most natural query method is using native queries. Basically you just pass in a instance of a predicate, which filters the objects out you want.
ObjectContainer container = Db4oEmbedded.openFile("databaseFile.db4o"); try { List<Pilot> pilots = container.query(new Predicate<Pilot>() { public boolean match(Pilot o) { return o.getName().equals("Joe"); } }); for (Pilot pilot : pilots) { System.out.println(pilot.getName()); } } finally { container.close(); }
Updating objects is also easy. First you query for the object which you want to update. Then you change the object and store it again in the database.
ObjectContainer container = Db4oEmbedded.openFile("databaseFile.db4o"); try { List<Pilot> pilots = container.query(new Predicate<Pilot>() { public boolean match(Pilot o) { return o.getName().equals("Joe"); } }); Pilot aPilot = pilots.get(0); aPilot.setName("New Name"); // update the pilot container.store(aPilot); } finally { container.close(); }
Use the delete-operation to delete objects.
ObjectContainer container = Db4oEmbedded.openFile("databaseFile.db4o"); try { List<Pilot> pilots = container.query(new Predicate<Pilot>() { public boolean match(Pilot o) { return o.getName().equals("Joe"); } }); Pilot aPilot = pilots.get(0); container.delete(aPilot); } finally { container.close(); }