Skip Headers

# Modifying an Object

Previous

Next

In Example: Modifying an Object, a `Pet` is read prior to a unit of work: the variable `pet` is the cache copy clone for that `Pet`. Inside the unit of work, register the cache copy to get a working copy clone. We then modify the working copy clone and commit the unit of work.

Modifying an Object

    // Read in any pet
    Pet pet = (Pet)session.readObject(Pet.class);
    UnitOfWork uow = session.acquireUnitOfWork();
        Pet petClone = (Pet) uow.registerObject(pet);
        petClone.setName("Furry");
    uow.commit();

In Example: Modifying an Object: Skipping the Registration Step, we take advantage of the fact that you can query through a unit of work and get back clones, saving the registration step. However, the drawback is that we do not have a handle to the cache copy clone.

If we wanted to do something with the updated `Pet` after the commit transaction, we would have to query the session to get it (remember that after a unit of work is committed, its clones are invalid and must not be used).

Modifying an Object: Skipping the Registration Step

    UnitOfWork uow = session.acquireUnitOfWork();
        Pet petClone = (Pet) uow.readObject(Pet.class);
        petClone.setName("Furry");
    uow.commit();

Both approaches produce the following SQL:

    UPDATE PET SET NAME = 'Furry' WHERE (ID = 100)

Take care when querying through a unit of work. All objects read in the query are registered in the unit of work and therefore will be checked for changes at commit time. Rather than do a `ReadAllQuery` through a unit of work, it is better for performance to design your application to do the `ReadAllQuery` through a session, and then register in a unit of work only the objects that need to be changed.