Skip Headers

# Maintaining Bidirectional Relationships

Previous

Next

When one-to-one or many-to-many relationship is bidirectional, you must maintain the back pointers as the relationships change.

TopLink automatically maintains the relationship between two entity beans.

To set the back pointer manually, do one of the following:

- Code the entity bean to maintain the back pointer when the relationship is established or modified (recommended).

- Code the client to explicitly set the back pointer.

If you code the entity bean to set back pointers, the client is freed of this responsibility. This has the advantage of encapsulating this maintenance implementation in the bean.

In a one-to-many relationship, a source bean might have several dependent target objects. For example, an `EmployeeBean` might own several dependent `PhoneNumber` instances. When you add a new dependent object (a `PhoneNumber`, in this example) to an employee, you must set the `PhoneNumber` instance's back pointer to its owner (the employee). Maintaining a one-to-many relationship in the entity bean involves getting the local object reference from the context of the `EmployeeBean`, and then updating the back pointer as Example: Setting the Back-Pointer in the Entity Bean shows.

Setting the Back-Pointer in the Entity Bean

    // obtain owner and phoneNumber
    owner = empHome.findByPrimaryKey(ownerId);
    phoneNumber = new PhoneNumber("cell", "613", "5551212");
    // add phoneNumber to the phoneNumbers of the owner
    owner.addPhoneNumber(phoneNumber);

    // Maintain the relationship in the Employee's addPhoneNumber method
    public void addPhoneNumber(PhoneNumber newPhoneNumber) {
        // get, then set the back pointer to the owner
        Employee owner = (Employee)this.getEntityContext().getEJBLocalObject();
        newPhoneNumber.setOwner(owner);
        // add new phone
        getPhoneNumbers().add(newPhoneNumber);
    }

For more information, see the following:

- Configuring Bidirectional Relationship

- "Directionality"