Automatic Deactivation


The use of depth parameter in deactivate call from the previous example directly affects performance: the less is the depth the less objects will need to be re-read from the database and the better the performance will be. Ideally we only want to deactivate the objects that were changed in the rolled-back transaction. This can be done by providing a special class for db4o configuration. This class should implement RollbackStrategy/IRollbackStrategy interface and is configured as part of Transparent Persistence support:

TPRollback.java: rollbackDeactivateStrategy
1private static class RollbackDeactivateStrategy implements RollbackStrategy { 2 public void rollback(ObjectContainer container, Object obj) { 3 container.ext().deactivate(obj); 4 } 5 }
TPRollback.java: configureTPForRollback
1private static Configuration configureTPForRollback() { 2 Configuration configuration = Db4o.newConfiguration(); 3 // add TP support and rollback strategy 4 configuration.add(new TransparentPersistenceSupport( 5 new RollbackDeactivateStrategy())); 6 return configuration; 7 }

RollbackDeactivateStrategy#rollback method will be automatically called once per each modified object after the rollback. Thus you do not have to worry about deactivate depth anymore - all necessary deactivation will happen transparently preserving the best performance possible.

TPRollback.java: modifyWithRollbackStrategy
01private static void modifyWithRollbackStrategy() { 02 ObjectContainer container = database(configureTPForRollback()); 03 if (container != null) { 04 try { 05 // create a car 06 Car car = (Car) container.queryByExample(new Car(null, null)) 07 .get(0); 08 Pilot pilot = car.getPilot(); 09 System.out.println("Initial car: " + car + "(" 10 + container.ext().getID(car) + ")"); 11 System.out.println("Initial pilot: " + pilot + "(" 12 + container.ext().getID(pilot) + ")"); 13 car.setModel("Ferrari"); 14 car.changePilot("Michael Schumacher", 123); 15 container.rollback(); 16 System.out.println("Car after rollback: " + car + "(" 17 + container.ext().getID(car) + ")"); 18 System.out.println("Pilot after rollback: " + pilot + "(" 19 + container.ext().getID(pilot) + ")"); 20 } finally { 21 closeDatabase(); 22 } 23 } 24 }

Note, that RollbackDeactivateStrategy only works for activatable objects. To see the different you can comment out Activatable implementation in Id class (id value will be preserved in the cache).