Skip Headers

# Associating a New Source to an Existing Target Object

Previous

Next

This section describes how to associate a new source object with an existing target object with one-to-many and one-to-one relationships.

TopLink follows all relationships of all registered objects (deeply) in a unit of work to calculate what is new and what has changed. This is known as persistence by reachablity. In "Associating a New Target to an Existing Source Object", we saw that when you associate a new target with an existing source, you can choose to register the object or not. If you do not register the new object, it is still reachable from the source object (which is a clone, hence it is registered). However, when you need to associate a new source object with an existing target, you must register the new object. If you do not register the new object, then it is not reachable in the unit of work, and TopLink will not write it to the database.

For example, the code shown in Example: Associating a New Source to an Existing Target Object shows how to create a new `Pet` and associate it with an existing `PetOwner`.

Associating a New Source to an Existing Target Object

    UnitOfWork uow = session.acquireUnitOfWork();
        PetOwner existingPetOwnerClone =
            (PetOwner)uow.readObject(PetOwner.class);

        Pet newPet = new Pet();
        Pet newPetClone = (Pet)uow.registerObject(newPet);
        newPetClone.setId(900);
        newPetClone.setType("Lizzard");
        newPetClone.setName("Larry");
        newPetClone.setPetOwner(existingPetOwnerClone);
    uow.commit();

This generates the proper SQL:

    INSERT INTO PET (ID, NAME, TYPE, PET_OWN_ID) VALUES (900, 'Larry', 'Lizzard', 400)

In this situation, you should register the new object and work with the working copy of the new object. If you associate the new object with the `PetOwner` clone without registering, it will not be written to the database. If you are in a situation where you want to associate the `PetOwner` clone with the new `Pet` object, use the advanced API `registerNewObject` as described in "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".

If you fail to register the clone and accidentally associate the cache version of the existing object with the new object, then TopLink will generate an error which states that you have associated the cache version of an object ("from a parent session") with a clone from this unit of work. You must work with working copies in units of work.