I am having some trouble understanding the difference between @OneToMany and @ManyToMany. When I use @OneToMany it defaults to create a JoinTable and if you add the mappedBy attribute you will have bidirectional relationship between two entities.
I have a Question that may belong to many Categories, and one Category may belong to many Questions. I don’t understand if I should use @ManyToMany or @OneToMany because for me it seems exactly the same thing, but it is probably not.
Could somebody explain it?
Well, the difference is in the design you’re trying to reflect using objects.
In your case, every
Questioncan be assigned to multipleCategories– so that’s a sign of@*ToManyrelationship. Now you have to decide if:Categorycan have only oneQuestionassigned to it (it will result in a unique constraint which means that no other Category can refer the same Question) – this will be@OneToManyrelationship,Categorycan have multipleQuestionsassigned to it (there will be no unique constraint in theCategorytable) – this will be@ManyToManyrelationship.@OneToMany (Question -> Category)
This relationship can be represented by join table only if you explicitly define so using
@JoinTableor when it is a unidirectional relationship in which the owning side is the ‘One’ side (it means that in theQuestionentity you have a collection ofCategories, but in theCategoriesyou don’t have any reference to theQuestion).If you think about it, it seems quite reasonable that the join table is used. There is no other way the DBMS could save a connection between one row in
Questiontable with multiple rows inCategoriestable.However, if you would like to model a bidirectional relationship you need to specify that the
Category(‘Many’ side) is the owning side of the relationship. In this case the DBMS can create a join column with foreign key in theCategorytable because eachCategoryrow can be connected with only oneQuestion.In this way you don’t have any join table but simple foreign keys (still, as pointed at the beginning, you can force to create the join table using
@JoinTable).@ManyToMany
This relationship must be represented as a join table. It basically works very similar to the unidirectional
@OneToManyrelationship, but in this case you may have multiple rows fromQuestionjoined with multiple rows fromCategories.