Transactions

When managing the persistence of objects using a PersistenceManager it is normal to handle all datastore operations in a transaction. For this reason each PersistenceManager has its own transaction. Consequently a typical JDO persistence method will look something like this

PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
try
{
    tx.begin(); // Start the PM transaction

    ... perform some persistence operations

    tx.commit(); // Commit the PM transaction
}
finally
{
    if (tx.isActive())
    {
        tx.rollback(); // Error occurred so rollback the PM transaction
    }
}

JDO supports the two main forms of transaction

  • Transactions can lock all records in a datastore and keep them locked until they are ready to commit their changes. These are known as Pessimistic (or datastore) Transactions
  • Transactions can simply assume that things in the datastore will not change until they are ready to commit, not lock any records and then just before committing make a check for changes. These are known as Optimistic Transactions.

You select the type of transaction to be used by a PersistenceManager (PM) either by setting the PMF property javax.jdo.option.Optimistic, or on the transaction you call

pm.currentTransaction().setOptimistic(true);