...

/

Many-to-Many Unidirectional Relationship

Many-to-Many Unidirectional Relationship

Learn about implementing a many-to-many relationship using a join table.

Every tournament has some playing categories like singles and doubles for men and/or ladies. In addition, all four grand slam tournaments have the mixed doubles category. Other less known categories are wheelchair tennis and beach tennis. This scenario fits well into the many-to-many relationship where many categories are part of a tournament and many tournaments have the same playing categories.

Press + to interact
A tournament has many categories and a category is included in many tournaments.
A tournament has many categories and a category is included in many tournaments.

We have already created the Tournament class. In this lesson, we will create the Category class and then join the two with a many-to-many relationship. In databases, this relationship is modelled using a join table which has the primary keys of both tables in the relationship.

Press + to interact
Many-to-many relationship is implemented using a join table.
Many-to-many relationship is implemented using a join table.

We will also model two real life constraints.

  • The first one is that one playing category should appear only once in the category table (we don’t want multiple entries for the same category).

  • The second constraint is that when a tournament entry is deleted, the associated playing categories should not be deleted and vice versa.

For the many-to-many database relationship example, create a package manytomany and copy all the files from the bi package inside the onetomany package. These include the Player, PlayerProfile, Registration, Tournament and DatabaseRelationshipsApplication classes and the associated repository, service, and controller classes.

Creating entity

We will begin by creating a new class, Category in the io.datajek.databaserelationships.manytomany package. This class has two fields, id and name, where id ...