Skip to main content

Many To Many Mapping in Hibernate Annotation

Points To Remember


There are two ways to create hibernate many to many relational mappings in Hibernate. We will discuss both of them in detail here.
  1. First one is to use default hibernate mapping to create and manage these relations.
  2. By creating a new domain that will manage these relations for us.
Suppose we want to have a simple User and Role mapping where a user can have multiple roles and a role can be assigned to multiple users. Then we can create and manage these relations in the following ways.

Strategy 1 : Default Hibernate Mappings

You can use this strategy as applied like shown in this article. This will make the hibernate to deal with all the mappings and operations like save , update, fetch etc.

Advantage : This will make hibernate responsible for the mapping and operations like save, fetch, update etc.

Disadvantage : You will not have control over the mapped relation. You will not be able to query the table it will create for mapping.

Strategy 2 : Using Domain to Handle Mappings

This strategy can be applied like shown in this article . So this will actually help us take control of the mappings and will give more control on how we manage and use this.

Advantage : This approach can be used when you want to take control of the mapping from hibernate to your own hands or when you want to use the mappings with some additional data related to the mappings.

Disadvantage : In this approach you will have to make sure that you save the mappings on your own. Hibernate will not fetch or save these mappings on its own.

Comments