Skip Headers

# Associating an Existing Source to an Existing Target Object

Previous

Next

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

As shown in Example: Associating an Existing Source to Existing Target Object, associating existing objects with each other in a unit of work is as simple as associating objects in Java. Just remember to only work with working copies of the objects.

Associating an Existing Source to Existing Target Object

    // Associate all VetVisits in the database to a Pet from the database
    UnitOfWork uow = session.acquireUnitOfWork();
        Pet existingPetClone = (Pet)uow.readObject(Pet.class);
        Vector allVetVisitClones;
        allVetVisitClones = (Vector)uow.readAllObjects(VetVisit.class);
        Enumeration enum = allVetVisitClones.elements();
        while(enum.hasMoreElements()) {
            VetVisit vetVisitClone =(VetVisit)enum.nextElement();
            existingPetClone.getVetVisits().addElement(vetVisitClone);
            vetVisitClone.setPet(existingPetClone);
        };
    uow.commit();

The most common error when associating existing objects is failing to work with the working copies. If you accidentally associate a cache version of an object with a working copy you will get an error at commit time indicating that you associated an object from a parent session (the cache version) with a clone from this unit of work.

Example: Associating Existing Objects shows another example of associating an existing source to an existing target object.

Associating Existing Objects

    // Get an employee read from the parent session of the unit of work
    Employee employee = (Employee)session.readObject(Employee.class)

    // Acquire a unit of work
    UnitOfWork uow = session.acquireUnitOfWork();
    Project project = (Project) uow.readObject(Project.class);

    /* When associating an existing object (read from the session) with a clone, we must make sure we register the existing object and assign its clone into a unit of work */

    /* INCORRECT: Cannot associate an existing object with a unit of work clone. A QueryException will be thrown */
    //project.setTeamLeader(employee);

    /* CORRECT: Instead register the existing object then associate the clone */
    Employee employeeClone = (Employee)uow.registerObject(employee);
    project.setTeamLeader(employeeClone);
    uow.commit();