Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate - How to reference a collection from a join table?

Tags:

hibernate

I've got a model where exam has a many to many mapping to questions, and each question_exam combination can have many results (for example question 1 in exam1 can be answered 10 times, therefore will have 10 results). The basic model classes are below

Exam{
    exam_id
}

Question{
    question_id
}    

Result{
id
    exam_id
    question_id
    dateentered
}

I can create the relationship between exam and questions easily, hibernate uses a join table I've created called exams_questions. My problem is linking results to the exams_questions table. For example if I want to get an exam object that has the following structure: Exam - Questions - Results (only for the questions related to the exam)

How do I write my mappings to allow my to get an Exam an as object with a collecton of questions, and those questions have collections of results (only for that exam)?

I've looked at join tables with extra columns and ternary associations but I don't think they provide me with what I need.

Thanks in advance

like image 832
user1836045 Avatar asked Dec 10 '25 07:12

user1836045


1 Answers

You should have the following associations:

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;
}

The above maps each association as a bidirectional association, but you could of course choose to makes them unidirectional.

like image 93
JB Nizet Avatar answered Dec 12 '25 20:12

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!