Many to Many
Easily the most complicated relationship currently used in an enterprise application, many-to-many relationships employ a third table, often referred to as a join table, to complete the relationship. This join table holds a reference to the primary key to each of the tables on either side of the relationship and allows many "parents" to have many "children"—and can even share children.
To define this relationship in XDoclet, both sides of the relationship need to be defined as target-multiple, as seen in the code below:
/** * @ejb.interface-method * * @ejb.relation name="Parents-to-Children" * role-name="Parent-has-many-Children" * target-ejb="ExampleChildBean" * target-role-name="Child-has-many-parents" * target-multiple="yes" * * @jboss.relation-mapping style="relation-table" * * @jboss.relation-table table-name="ParentChildrenJoin" * * @jboss.relation related-pk-field="ID" * fk-column="parentID" * fk-constraint="false" */ public abstract Collection getChildren(); /** * @ejb.interface-method */ public abstract void setChildren(Collection c);
And the methods in the "child" entity:
/** * @ejb.interface-method * * @ejb.relation name="Parents-to-Children" * role-name="Child-has-many-parents" * target-ejb="ExampleBean" * target-role-name="Parent-has-many-Children" * target-multiple="true" * * @jboss.relation-mapping style="relation-table" * * @jboss.relation-table table-name="ParentChildrenJoin" * * @jboss.relation fk-column="parentID" * related-pk-field="ID" * fk-constraint="false" * * @return */ public abstract Collection getParents(); /** * @ejb.interface-method */ public abstract void setParents(Collection el);
The primary difference in this relationship setting is JBoss-specific. The jboss.relation-mapping tag and jboss.relation-table tags instruct JBoss to use a join table and what to name that table. The other tag change is the addition of @jboss.relation fk-constraint="false". This tag instructs JBoss to not force a foreign key constraint between the tables.