Hibernate Many to Many Mapping

Hibernate Many to Many is a combination of one-to-many and reverse of one-to-many. When creating a POJO class, one need to use the reference variable of type collection. Hibernate Many to Many relationship means applying one-to-many relationship on both sides in two POJO classes means it is bidirectional. Collection property will be used while using Hibernate Many to Many mapping.
In a Database, Hibernate Many to Many relationships is not applicable to two tables. So use the third table. This third table is called a Join table. It will store foreign keys of two tables. Key points of hibernate mappings are:
- Hibernate Many to Many – Join table is utilized in many to many mapping to keep the primary key as foreign key.
- Join table will have only foreign keys.
Many-to-many mapping is an association between two entities where one instance of an entity is associated with the multiple instances of another entity and vice-versa. A many-to-many relationship always has two sides called an owning side and a non-owning side. The Join
operation of a table is defined on the owning side and the owning side has a field that stores collection of target entities.
The many-to-many association can be either unidirectional or bidirectional.
- In unidirectional association, only source entity has a relationship field that refers to the target entities. We can navigate this type of association from one side
- In bi-directional association, each entity has a relationship field that refers to each other. We can navigate this type of association from both sides
For example, we can have a cart and item table and cart_items table for many-to-many mapping. Every cart can have multiple items and every item can be part of multiple carts, so we have a many to many mapping here.

Cart_Items table doesn’t have any extra columns, actually it doesn’t make much sense to have extra columns in many-to-many mapping table. But if you have extra columns, the implementation changes a little bit and we will look into that in another post.
