Rollback And Cache


Suppose we have Car, Pilot and Id classes stored in the database. Car class is activatable, others are not. We will modify the car and rollback the transaction:

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

If the transaction was going on normally (commit), we would have had the car modified in the database as it is supported by Transparent Persistence. However, as the transaction was rolled back - no modifications should be done to the database. The result that is printed to the screen is taken from the reference cache, so it will show modified objects. That is confusing and should be fixed:

TPRollback.java: modifyRollbackAndCheck
01private static void modifyRollbackAndCheck() { 02 ObjectContainer container = database(configureTP()); 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 container.deactivate(car, Integer.MAX_VALUE); 17 System.out.println("Car after rollback: " + car + "(" 18 + container.ext().getID(car) + ")"); 19 System.out.println("Pilot after rollback: " + pilot + "(" 20 + container.ext().getID(pilot) + ")"); 21 } finally { 22 closeDatabase(); 23 } 24 } 25 }

Here we've added a deactivate call for the car object. This call is used to clear the reference cache and its action is reversed to activate.

We've used Integer.MAX_VALUE/Int32.MaxValue to deactivate car fields to the maximum possible depth. Thus we can be sure that all the car fields will be re-read from the database again (no outdated values from the reference cache), but the trade-off is that all child objects will be deactivated and read from the database too. You can see it on Pilot object. This behaviour is preserved for both activatable and non-activatable objects.