Relationship Cardinality in Data Modeling

Cardinality describes how many instances of one entity may be associated with instances of another. It helps determine how relationships are represented and constrained in a database and in application code.

A relationship’s cardinality describes the allowed number of related instances. Common patterns are one-to-one, one-to-many, and many-to-many. For example, a customer may place many orders, while each order belongs to one customer.

Cardinality can also include minimum participation. A customer might have zero or more orders, while an order might be required to have exactly one customer. The minimum captures whether a relationship is optional; the maximum captures how many related instances are allowed.

Relational databases commonly represent one-to-many relationships with a foreign key on the “many” side. A one-to-one relationship typically also needs a uniqueness constraint on the foreign key. A many-to-many relationship is commonly represented using a separate join table containing foreign keys to both entities.

In Java, a collection often represents the many side, while a single reference represents the one side. Those field types communicate the intended object model, but they do not by themselves guarantee that stored data follows the relationship rules. Database constraints and application validation may also be needed.

Key points

Interview questions

What does cardinality mean in a data model?

Cardinality describes how many instances of one entity can be related to instances of another. Common forms are one-to-one, one-to-many, and many-to-many. A relationship can also specify minimum participation, such as whether a related entity is optional or required.

How would you model customers and orders if each order belongs to one customer and a customer can place many orders?

That is a one-to-many relationship from customer to order. In a relational database, the orders table would usually contain a foreign key to the customer table. If every order must have a customer, that foreign key should be required, typically using a NOT NULL constraint.

How is a many-to-many relationship usually represented in a relational database?

A common approach is a join table with foreign keys pointing to each related table. Each row in the join table represents one association. If the association has its own attributes, such as a quantity or start date, it is often useful to model it as its own entity rather than treating it as a bare link.

Does declaring a Java field as a List enforce a one-to-many relationship?

No. A `List` indicates that the Java object can hold multiple references, but it does not enforce database integrity. The persistence mapping and database constraints determine which relationships can be stored. Application code may also need to keep both sides of a bidirectional relationship consistent.