Skip Headers

# Associating Without Reference to the Cache Object

Previous

Next

Example: Associating Without Reference to the Cache Object shows the first way of associating a new target with an existing source.

Associating Without Reference to the Cache Object

    UnitOfWork uow = session.acquireUnitOfWork();
        Pet petClone = (Pet)uow.readObject(Pet.class);

        PetOwner petOwner = new PetOwner();
        petOwner.setId(400);
        petOwner.setName("Donald Smith");
        petOwner.setPhoneNumber("555-1212");

        VetVisit vetVisit = new VetVisit();
        vetVisit.setId(500);
        vetVisit.setNotes("Pet was shedding a lot.");
        vetVisit.setSymptoms("Pet in good health.");
        vetVisit.setPet(petClone);

        petClone.setPetOwner(petOwner);
        petClone.getVetVisits().addElement(vetVisit);
    uow.commit();

This executes the proper SQL:

    INSERT INTO PETOWNER (ID, NAME, PHN_NBR) VALUES (400, 'Donald Smith', '555-1212')
    UPDATE PET SET PET_OWN_ID = 400 WHERE (ID = 100)
    INSERT INTO VETVISIT (ID, NOTES, SYMPTOMS, PET_ID) VALUES (500, 'Pet was shedding a lot.', 'Pet in good health.', 100)

When associating new objects to existing objects, the unit of work treats the new object as if it were a clone. That is, after the commit transaction:

    petOwner != session.readObject(petOwner)

For a more detailed discussion of this fact, see "Using registerNewObject").

Note: You cannot use `UnitOfWork` methods `registerObject`, `registerNewObject`, or `registerExistingObject` with an aggregate object (see "Relational Aggregate Descriptors"). Doing so will raise a `ValidationException` or other errors at commit time. For more information, see "Working With Aggregates".

Therefore, after the unit of work commit transaction, the variables `vetVisit` and `petOwner` no longer point to their respective cache objects; they point at working copy clones.

If you need the cache object after the unit of work commit transaction, you must query for it or create the association with a reference to the cache object (as described in "Associating With Reference to the Cache Object").