Container Managed Relationships (CMR)

In this example, the House CMP bean is related to the Student CMP bean. Since a student can live in only one house, but one house can be the home of several students, this is a one-to-many relation.

We can have Resin-CMP manage this relationship for us so that we don't have to use JDBC to find related entities. Our two beans in this example will use the following tables: ``

        CREATE TABLE one2many_students (
          name VARCHAR(250) NOT NULL,
          house VARCHAR(250),

          PRIMARY KEY(name)
        );

        CREATE TABLE one2many_houses (
          name VARCHAR(250) NOT NULL,

          PRIMARY KEY(name)
        );

Setting up the deployment descriptor

All setup related to CMR is done in the <relationships> section. We set up our one2many relationship like this:

`<relationships>
<ejb-relation>
<ejb-relationship-role>
<relationship-role-source>
<ejb-name>one2many_StudentBean</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>house</cmr-field-name>
</cmr-field>
</ejb-relationship-role>
<ejb-relationship-role>
<relationship-role-source>
<ejb-name>one2many_HouseBean</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>studentList</cmr-field-name>
</cmr-field>
</ejb-relationship-role>
</ejb-relation>
</relationships>
`

Every <ejb-relation> has two participating entity beans. Their role in the relation is defined within a <ejb-relationship-role> section. Use the <ejb-name> tag to describe which entity the <ejb-relationship-role> block belongs to.

CMR fields are "virtual" fields in an Entity Bean that are being maintained by the container.

Writing code for the CMR fields

For the HouseBean, we have defined `studentList` as a CMR field. We need to match this with a method declaration in HouseBean.java:

        abstract public Collection getStudentList();

which Resin-CMP will implement for us. For adding Students to the house, instead of defining a set-method, we can simply add to the Collection:

          // adding a student to a house
          house.getStudentList().add(student);

The case is a bit different for StudentBean because here the CMR field, `house`, has a multiplicity of one. Our CMR accessor method will not return a collection. Instead we define two methods:

        abstract public House getHouse();
        abstract public void setHouse(House house);

In this example of a one2many relation, we need to make sure that each student entity has as its `house` value a String that can be matched to the primary key of one house entity. Otherwise, Resin-CMP will not be able to associate house and student records in the database.