122 Transaction management Here we now see the
Thursday, October 26th, 2006Transaction strategies 123 A code example of this is shown below: Transaction t = pm.currentTransaction(); t.setOptimistic(true); t.begin() try { String bpKey = “123″; // some valid key value BusinessPartner bp = (BusinessPartner) pm.getObjectById(bkKey); String name = bp.getName(); // bp transitions to Persistent-Nontransactional // do some work here which might take an extended time; // display the name // to the user and allow them to change it, before which // the user might go out for lunch! // retrieve the instance and update pm.refresh(bp); // bp remains Persistent-Nontransactional bp.setName(name); // bp transitions to Persistent-Dirty } catch (Exception e) { // rollback the transaction if it is still active if (t.isActive()) t.rollback(); } finally { // commit the transaction if it is still active try { // commit the transaction if it is still active if (t.isActive()) t.commit(); } catch (JDOUserException je) { // transaction rolled back advise the user that // the work they did has // not been saved and must be done again } } The instance is refreshed immediately before it is updated. The chance of concurrency assumptions being invalid is greatly reduced. However, what we have is no longer a true optimistic transaction strategy instead we have a last commit wins situation. This is equivalent to using one short-lived pessimistic transaction to read an instance, allowing the read data to be updated non-transactionally, and then committing that to the database without any regard for changes that may have occurred in the interim.
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra servlet hosting services