Mapping value in junction table to Entity

前端 未结 2 542
太阳男子
太阳男子 2020-12-14 13:57

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

相关标签:
2条回答
  • 2020-12-14 14:26

    As you say, adding the role to the user doesn't make sense since the user may have many courses, and adding the role to the course won't work because a course may have many users.

    So you need another entity. Something like:

    @Entity
    @Table(name = "COURSE_USERS")
    // @pkJoinColumns = probably some combination of user/course
    public class CourseUser {
    
    @Column(name = "ROLE")
    private Character role;
    
    @Column(name = "USERS_PK1")
    private User user;
    
    @Column(name = "CRSMAIN_PK1")
    private Course course;
    }
    

    And each User would have many CourseUsers and each Course would have many CourseUsers.

    0 讨论(0)
  • 2020-12-14 14:30

    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.

    @Entity
    @Table(name = "COURSE_USERS")
    @IdClass(CourseAssignmentId.class)
    public class CourseAssignment {
        @Id
        @ManyToOne
        @JoinColumn(name="USERS_PK1")
        private User user;
        @Id
        @ManyToOne
        @JoinColumn(name="CRSMAIN_PK1")
        private Course course;
    
        @Column(name = "ROLE")
        private Character role;
    }
    //and then of course IdClass, because combined key:
    @Embeddable
    public class CourseAssignmentId implements Serializable{
        @Column(name="USERS_PK1")
        private Long user;
    
        @Column(name="CRSMAIN_PK1")
        private Long course;
    }
    
    
    User { ..
    
        @OneToMany(mappedBy = "user")
        private Collection<CourseAssignment> courseAssignments;
    ...
    }
    
    Course {..
       @OneToMany(mappedBy = "course")
       private Collection<CourseAssignment> course;
    
    ..
    }
    

    And of course remove those existing relationship connected attributes.

    0 讨论(0)
提交回复
热议问题