I have an entity called User with two many-to-many relationships: User -mtm - Role and User -mtm - Course
public class User {
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "users_roles",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id")})
private List<Role> userRoles;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "users_courses",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "course_id", referencedColumnName = "id")})
private List<Course> orderedCourses;
}
In Course entity:
public class Course {
@ManyToMany(mappedBy = "orderedCourses")
private List<User> participants;
}
It looks similar in the Role
entity.
When user with e.g. two roles assigned enrolls himself to some course (means that course is added to his orderedCourses
list), he gets this course twice.
So the user with two roles gets registered for the same course twice, user with 3 roles gets it three times etc.
It is noticeable in the junction table in the database. (one user has the same course few times which is unacceptable).
Looks like one ManyToMany
relationship has an impact on another. But I don't know what is wrong.
Everything is persisted to MySQL database by Hibernate (via Spring Data JPA)