Many-to-many relationships occur when each record in an entity may have many linked records in another entity and vice-versa. In this blog post, I am taking the example of employee and meeting relationship. An employee can have many meetings and of-course a meeting has many employees, since one employee can do meeting alone😉
So we need 2 entities, Employee where we will keep a collection of meeting object reference and vice a versa we will keep the collection of emplyee in meeting object.
Let us understand the annotations we used here to map Many to many relationship.
@ManyToMany – Is used to create many-to-many relationship between
Meeting entities. If the Collection is defined using generics to specify the element type, the associated target entity class does not need to be specified; otherwise it must be specified. Every many-to-many association has two sides, the owning side and the non-owning, or inverse, side. The join table is specified on the owning side. If the association is bidirectional, either side may be designated as the owning side.
Note that in above entity classes, Employee is defined as relationship owner as
@JoinColumn is define in
Employee class and
mappedBy is specified in Meeting class.
@JoinTable – Is used to define the join table (link table) for many-to-many relationship. It is specified on the owning side of a many-to-many association, or in a unidirectional one-to-many association. In this case the join table is
If the JoinTable annotation is missing, the default values of the annotation elements apply. The name of the join table is assumed to be the table names of the associated primary tables concatenated together (owning side first) using an underscore.
@JoinColumn – Is used to define the join column (linking column) in both main tables.
Note that we have used SET to map meetings with employee and vice versa. A is similar to except that it can only store unique objects. That means no duplicate elements can be contained in a set. When you add the same element to a set for second time, it will replace the old one. A set is unordered by default but we can ask it to be sorted. The corresponding type of a in Java is