Relationships are special DataObject properties that reference other "related" objects. Semantically there are two types of relationships - to-one pointing to just a single DataObjects (e.g. Painting.toArtist), and to-many pointing to a collection of DataObjects of the same base type (e.g. Artist.paintingArray).

To-One Relationships

"Get" methods for to-one relationships return the target DataObject. If the object is not in memory yet, it will be fetched on demand. Modifying to-one relationships is no different from modifying attributes - just a simple call to a "set" method:

Painting painting;

// obtain artist for a given painting
Artist originalArtist = painting.getToArtist();

// replace with a new artist
Artist newArtist = (Artist)context.createAndRegisterNewObject(Artist.class);
painting.setToArtist(newArtist);

// or remove Artist at all...
// painting.setToArtist(null);
When adding or removing an object from any kind of relationship, Cayenne will locate and modify an existing reverse relationship as appropriate.

To-Many Relationships

"Get" methods for to-many relationships return Lists of DataObjects. Just like individual DataObjects, such lists are also resolved on demand (e.g. when a user tries to read an element from the list). For modification there are special "addTo..." and "removeFrom..." methods:

Artist artist;

// obtain a list of paintings
List paintings = artist.getPaintingArray();

// remove the first painting
if(paintings.size() > 0) {
   Painting firstPainting = (Painting)paintings.get(0);
   artist.removeFromPaintingArray(firstPainting);
}

// add a new painting
Painting newPainting = (Painting)context.createAndRegisterNewObject(Painting.class);
artist.addToPaintingArray(newPainting);
While to-many relationships in Cayenne are represented by Lists, they are really ordered Sets, as they are not allowed to contain the same object more than once.