|
The code for the Item class (the other end of the many-to-many association) is similar to the code for the Category class. We add the collection attribute, the standard accessor methods, and a method that simplifies relationship management (you can also add this to the Category class).
The addCategory() of the Item method is similar to the addChildCategory convenience method of the Category class. It’s used by a client to manipulate the relationship between Item and a Category. For the sake of readability, we won’t show convenience methods in future code samples and assume you’ll add them according to your own taste.
public class Category {
...
private Set items = new HashSet();
...
public Set getItems() {
return items;
}
public void setItems(Set items) {
this.items = items;
}
}
_______________________________________________________________
public class Item {
private String name;
private String description;
...
private Set categories = new HashSet();
...
public Set getCategories() {
return categories;
}
private void setCategories(Set categories) {
this.categories = categories;
}
public void addCategory(Category category) {
if (category == null)
throw new IllegalArgumentException("Null category");
category.getItems().add(this);
categories.add(category);
}
}
|
|