Hibernate - 如何从联接表引用集合?

3
我有一个模型,其中考试与问题具有多对多的映射关系,每个问题和考试组合都可以有多个结果(例如,在考试1中回答问题1可以有10个结果)。基本的模型类如下所示。
Exam{
    exam_id
}

Question{
    question_id
}    

Result{
id
    exam_id
    question_id
    dateentered
}

我可以轻松地创建试卷和问题之间的关系,Hibernate使用我创建的名为exams_questions的连接表。我的问题在于将结果链接到exams_questions表。例如,如果我想获取一个考试对象,其结构如下:
考试 - 问题 - 结果(仅针对与考试相关的问题)
我该如何编写映射以允许我获得一个考试对象,并具有问题集合,这些问题具有结果集合(仅适用于该考试)?
我已经查看了具有额外列和三元关联的连接表,但我认为它们没有提供我所需的内容。
提前感谢您。
1个回答

2
您应该具备以下的关联:
Exam {
    id;

    @OneToMany(mappedBy = "exam")
    Set<ExamQuestion> examQuestions;
}
Question {
    id;

    @OneToMany(mappedBy = "question")
    Set<ExamQuestion>;
}
ExamQuestion {
    id;

    @ManyToOne
    Question question;

    @ManyToOne
    Exam exam;

    @OneToMany(mappedBy="examQuestion")
    Set<Result> results;
}
Result {
    id

    @ManyToOne
    ExamQuestion examQuestion;
}

上述将每个关联都映射为双向关联,但您当然可以选择使它们成为单向关联。

非常感谢,这正是我需要的信息,让我走上了正确的道路。 - user1836045

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接