Like a table in a relational database, an entity bean may be related to other entity beans. With bean-managed persistence, the code that you write implements the relationships. But with container-managed persistence, the EJB container manages the relationships for you.
For instance, consider the cmpcustomer example that ships with the J2EE JDK. The example defines relationships between customers, addresses, and subscriptions. Each customer may have one or more addresses. A customer may also have zero or more subscriptions. Similarly, a single subscription may be associated with many customers. In order for this example to work correctly, the relationships between the entity beans representing these database tables must be configured correctly.
When you generate CMP entity beans from a database, the IDE automatically registers all of the container-managed relationships based on the relationships in the database. The CMP relationships are described in the module's ejb-jar.xml descriptor file. The IDE also automatically generates the necessary CMP fields in your source code.
When defining a CMP relationship, you may need to set the following properties.
Relationships between databases can either be unidirectional or multidirections. For example, in the above cmpcustomer example, the relationship between customers and the addresses is unidrectional, because the customer table references the address table but the address table does not reference the customer table. The relationship between subscriptions and customers, on the other hand, is multidirectional.
Multiplicity (also known as cardinality) describes how many instances of each side of the relationship there can be. Entity beans can have the following multiplicity:
Often, the existence of one table is often dependent on the existence of the table that references it. For example, in the above cmpcustomer example, you may add and delete individual addresses for a customer. Because an address instance must be associated to a customer, however, when you delete a customer, you are also automatically deleting all addresses associated to that customer.
The application server takes care of this automatically through the cascade delete setting. When you enable cascade delete in a relationship, all related bean instances are deleted when the bean referring to them is deleted.