Skip Headers

# Acquiring a Unit of Work With an External Transaction Service

Previous

Next

You use a unit of work to commit changes to a data source even when using an external transaction service. To ensure that only one unit of work is associated with a given transaction, use the `getActiveUnitOfWork` method to acquire a unit of work as shown in Example: Using a Unit of Work With an External Transaction Service.

Note: Although there are other ways to commit changes to a data source using an external transaction service, Oracle recommends using the `getActiveUnitOfWork` method.

The `getActiveUnitOfWork` method searches for an existing external transaction in the following way:

- If there is an active external transaction and a unit of work is already associated with it, return this unit of work.

- If there is an active external transaction with no associated unit of work, then acquire a new unit of work, associate it with the transaction, and return it.

- If there is no active external transaction in progress, return null.

If TopLink returns a unit of work that is not `null`, use it exactly as you would typically: the only exception is that you do not call the `commit` method (see "Using a Unit of Work When an External Transaction Exists").

If TopLink returns a `null` unit of work, start an external transaction explicitly through the `UserTransaction` interface.

Using a Unit of Work With an External Transaction Service

    // Read in any pet
    Pet pet = (Pet)clientSession.readObject(Pet.class);
    UnitOfWork uow = clientSession.getActiveUnitOfWork();
    if (uow == null) {
        throw new RuntimeException("No transaction started");;
    }
    Pet petClone = (Pet)uow.registerObject(pet);
    petClone.setName("Furry");