User's Manual

94 Chapter 9. Persistence Tutorial
9.8.2.1. Creating and Initializing Links
The DataAssociation.add(DataObject object) method is used when creating a link between
two objects. If the association was defined with the association keyword, this method returns the link
DataObject. The link DataObject can then be used to set any link attributes that have been defined.
This is illustrated in the following example:
// Put the current session in a variable for convenience.
Session ssn = SessionManager.getSession();
// Get a user.
DataObject user = ssn.retrieve(new OID("User", ...));
// Get a group.
DataObject group = ssn.retrieve(new OID("Group", ...));
// Get the "members" association so that we can add a member to the
// group.
DataAssociation members = (DataAssociation) group.get("members");
// Add the user to the association.
DataObject link = members.add(user);
java.util.Date now = new java.util.Date();
link.set("membershipDate", now);
// Persist the changes.
group.save();
Note
Only group.save() is called to persist the changes. Changes to the links are automatically persisted
when the parent object is saved.
9.8.2.2. Reading Link Attributes
The DataAssociationCursor.getLinkProperty(java.lang.String) method can be used to
read the values of a link attribute while iterating over a cursor.
// Put the current session in a variable for convenience.
Session ssn = SessionManager.getSession();
// Get a group.
DataObject group = ssn.retrieve(new OID("Group", ...));
// Get the members association.
DataAssociation members = (DataAssociation) group.get("members");
// Iterate over the members of the group and print out the
// membership date.
DataAssociationCursor cursor = members.getDataAssociationCursor();
while (cursor.next()) {
// Fetch the users email for the current row.
String email = cursor.get("email");
// Fetch the link property for the current row.
java.util.Date membershipDate =
(java.util.Date) cursor.getLinkProperty("membershipDate");