I have a USER table and a COURSE table. A USER can have many COURSES, and a COURSE many USERS. The junction table contains a ROLE value that determines what role the user has in a COURSE (i.e. Instructor, Student, etc.). I need to some how associate this role with the COURSE for each USER.
If I put the role in the Course class, it can’t work, since a Course has many users, and vice versa in the User class.
Here’s what I have so far:
@Entity
@Table(name = "USERS")
public class User {
@Id
@Column(name = "PK1")
private Long id;
@Column(name = "USER_ID")
private String userId;
@ManyToMany
@JoinTable(name = "COURSE_USERS",
joinColumns = @JoinColumn(name = "USERS_PK1", referencedColumnName = "PK1"),
inverseJoinColumns = @JoinColumn(name = "CRSMAIN_PK1", referencedColumnName = "PK1"))
private Collection<Course> courses;
...
@Entity
@Table(name = "COURSE")
@SecondaryTable(name = "COURSE_USERS",
pkJoinColumns = @PrimaryKeyJoinColumn(name = "CRSMAIN_PK1"))
public class Course {
@Id
@Column(name = "PK1")
private Long id;
// THIS PROBABLY WON'T WORK //
@Column(name = "ROLE", table = "COURSE_USERS")
private Character role;
@Column(name = "AVAILABLE_IND")
private boolean available;
@Column(name = "COURSE_NAME")
private String name;
@Transient
private String url;
...
Note: I cannot change the database schema, so the junction table is nonnegotiable.
There is third entity in your case, and it wants to come out. You can call it CourseAssignment. CourseAssignment will contain role, and ManyToOne relationship to both User and Role. And additionally of course OneToMany relationship from Course to CourseAssignment and from User to CourseAssignment.
Something like this will work (I didn’t tried it, so something can be missing, but you will get idea.
And of course remove those existing relationship connected attributes.