Referential Integrity

Db4o does not have a built-in referential integrity checking mechanism. Luckily EventRegistry gives you access to all the necessary events to implement it. You will just need to trigger validation on create, update or delete and cancel the action if the integrity is going to be broken.

For example, if Car object is referencing Pilot and the referenced object should exist, this can be ensured with the following handler in deleting() event:

CallbacksExample.java: testIntegrityCheck
01private static void testIntegrityCheck(){ 02 fillDB(); 03 final ObjectContainer container = Db4o.openFile(DB4O_FILE_NAME); 04 try { 05 EventRegistry registry = EventRegistryFactory.forObjectContainer(container); 06 // register an event handler, which will stop deleting a pilot when it is referenced from a car 07 registry.deleting().addListener(new EventListener4() { 08 public void onEvent(Event4 e, EventArgs args) { 09 CancellableObjectEventArgs cancellableArgs = ((CancellableObjectEventArgs) args); 10 Object obj = cancellableArgs.object(); 11 if (obj instanceof Pilot){ 12 Query q = container.query(); 13 q.constrain(Car.class); 14 q.descend("pilot").constrain(obj); 15 ObjectSet result = q.execute(); 16 if (result.size() > 0) { 17 System.out.println("Object " + (Pilot)obj + " can't be deleted as object container has references to it"); 18 cancellableArgs.cancel(); 19 } 20 } 21 } 22 }); 23 24 // check the contents of the database 25 ObjectSet result = container.get(null); 26 listResult(result); 27 28 // try to delete all the pilots 29 result = container.query(Pilot.class); 30 while(result.hasNext()) { 31 container.delete(result.next()); 32 } 33 // check if any of the objects were deleted 34 result = container.get(null); 35 listResult(result); 36 } finally { 37 container.close(); 38 } 39 }
You can also add handlers for creating() and updating() events for a Car object to make sure that the pilot field is not null.