Many-to-Many Bidirectional Relationship
Learn how to change the unidirectional many-to-many relationship to a bidirectional relationship.
We'll cover the following...
In a bidirectional relationship, each side has a reference to the other. In our example, the Category
class did not have any reference to the Tournament
class. Now we will add a reference to the Tournament
class so that the relationship can be navigated from both sides. This will have no effect on the underlying database structure. The join table tournament_catogories already has the foreign keys of both the tournament and category tables, and it is possible to write SQL queries to get tournaments associated with a category.
For a many-to-many relationship, we can choose any side to be the owner. The relationship is configured in the owner side using the @JoinTable
annotation. On the inverse side we use the mappedBy
attribute to specify the name of the field that maps the relationship in the owning side. From the database design point of view, there is no owner of a many-to-many relationship. It would not make any difference to the table structure if we swap the @JoinTable
and mappedBy
.
We will begin by creating a List
of tournaments
in the Category
class, along with the getter and setter methods.
public class Category {//...private List<Tournament> tournaments = new ArrayList<>();//...public List<Tournament> getTournaments() {return tournaments;}public void setTournaments(List<Tournament> tournaments) {this.tournaments = tournaments;}@Overridepublic String toString() {return "Category [id=" + id + ", name=" + name + ", tournaments=" + tournaments + "]";}}
mappedBy
property
On the tournaments
field created above, use the @ManyToMany
annotation with the mappedBy
property. This shows the value that is used to ...