Search code examples
hibernatejpamany-to-manybidirectional-relation

Does a hibernate many to many relationship have to use the @ManyToMany annotation and use a join table?


I searched a lot of examples on google related to the Hibernate many to many relationship. I found that all posts use the join table annotation (@JoinTable) in this kind of relationship.

Do I have to use @JoinTable in a many to many?

If yes, why?

If not, how can I implement this relationship?


Solution

  • The answer to your question is yes, if you want to create a schema for a many-to-many association, using a join table is the only available solution.

    Why? - you need a join table (A.id <--> B.id) between the two entity tables (A & B) to map the association.

    An example could be student and teachers, a student entity would likely not have a teacher ID FK and a teacher entity would likely not contain a student ID FK

    I think this post will answer how to implement the relationship.

    Also take care with bidirectional association, If one side is to be the owner then one side is to be the inverse end (ie. it will be ignored when updating the relationship values in the association table): The side which has the mappedBy attribute is the inverse side. The side which doesn't have the mappedBy attribute is the owner.