Reputation: 1537
I am trying to understand what would be the better way to design 2 entities which has many-to-many relationship? In database there will be a connecting table between these two entities. But do i have to follow the same approach while creating my entities?
For example: User to User group
A user may belong to many group and a group may contain many user.
In relational database I will have 3 table like User, User2Group, Group
So when I am creating my JPA entities, should I have 3 entities for 3 table or just 2 entities by providing the proper annotation(@ManytoMany).
Since I am new to JPA, I am trying to understand good and bad side from following point of view:
Thanks, you input will be greatly appreciated.
Upvotes: 2
Views: 2416
Reputation: 691725
No, you don't need to map the join table as an entity. Just use the ManyToMany annotation:
public class User {
...
@ManyToMany
private Set<Group> groups;
}
public class Group {
...
@ManyToMany(mappedBy = "groups")
private Set<User> users;
}
You would only need to map the join table as an entity if it was not a pure join table, i.e. if it had additional information like, for example, the date when the user entered in the group.
The mapping has little incidence on the performance. What is important is how you use and query the entities, and how the database is designed (indices, etc.)
Upvotes: 6