桥表主要作为另一个表中的外键(JPA)

时间:2017-02-02 07:54:35

标签: database hibernate jpa database-design nhibernate-mapping

我正在设计学生注册数据库

Student-Table student_id (pk) //other attributes

Course-Table course_id (pk) //other attributes

Student_course-Table student_course_id(pk) course_id (fk) student_id (fk)

Lectrue-Table lecture_id(pk) student_course_id(fk - > student_course table) // other attributes

基本上我想存储哪个学生注册到哪个课程,并参加了特定课程的讲座。

Q1)这个设计是否正确?我应该使用Bridge表的主键作为另一个表中的外键。 Q2)我在学生< - >之间进行了很多次映射。在course_course< - >之间的过程和oneToMany讲座并得到以下错误:

org.hibernate.MappingException:外键必须与引用的主键具有相同的列数

知道怎么办吗?

// UPDATE实体类

@Entity
@Table(name = "STUDENT")
public class Student implements Serializable {

    @Id
    @Column(name = "STUDENT_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToMany(mappedBy = "students" ,cascade = CascadeType.ALL)
    @MapKey(name = "courseName")
    private Map<String, Course> courses;


}

@Entity
@Table(name = "COURSE", uniqueConstraints = @UniqueConstraint(columnNames = {"COURSE_NAME"}))
public class Course implements Serializable {

    @Id
    @Column(name = "COURSE_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;


    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "STUDENT_COURSE", joinColumns = {
            @JoinColumn(name = "COURSE_ID") }, inverseJoinColumns = {
                    @JoinColumn(name = "STUDENT_ID") })
    private Set<Student> students;

    @Column(name = "COURSE_NAME")
    private String courseName;
}

@Entity
@Table(name = "LECTURE")
public class Lecture {

    @Id
    @Column(name = "LECTURE_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;



    @ManyToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "STUDENT_COURSE_ID")
    private StudentCourse studentCourse;

}

@Entity
@Table(name = "STUDENT_COURSE")

public class StudentCourse {

    @Id
    @Column(name = "STUDENT_COURSE_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "STUDENT_ID")
    private Long studentId;

    @Column(name = "COURSE_ID")
    private Long courseId;

    @OneToMany(mappedBy = "studentCourse")
    private Set<Lecture> lectures = new HashSet<Lecture>();
    }

0 个答案:

没有答案