1

I am facing difficulty to write hibernate mapping with java annotation for problem as given below.

Problem:

Tables

Table:Courses_Teachers
columns:
id
course_id
teacher_id
year(academic year)
Table: Courses_Students
columns:
id
course_id
student_id
year(academic year)
Table: Courses_Teachers_Students
course_teacher_id
course_student_id 

Classes

class Student {
    Map<Course,List<Teacher>> courseTeachersMap;  
}

Requirements

  • A course can be taught by multiple teachers to same student group .
  • A course is assigned to a grade level.
  • A grade level can have multiple student groups who are assigned different set of teachers for a course.

Please suggest me how to specify annotation for courseTeachersMap property in class student.

1 Answer 1

2

It is possible to map a ManyToMany association using a Map, and a typicall use case for this kind of mapping is when you have a ternary association. For example, if you have:

STUDENT_TEACHER_COURSE
STUDENT_ID(FK, PK)
TEACHER_ID(FK, PK)
COURSE_ID (FK, PK)

Then you could define the following mapping (assuming you're using a Hibernate Annotations < 3.5):

@Entity
public class Student {
    ...
    @ManyToMany
    @JoinTable(
        name="STUDENT_TEACHER_COURSE", 
        joinColumns= { @JoinColumn(name="STUDENT_ID") },
        inverseJoinColumns= { @JoinColumn(name="TEACHER_ID") }
    )
    @MapKeyManyToMany(joinColumns = @JoinColumn(name="COURSE_ID",unique = false))
    protected Map<Course,Teacher> teachers ;
    ...
}

But I don't think you can have a "nested" List<Teacher> as value inside the Map, I don't think Hibernate can map that and I'd consider getting the List from an entity instead.

References

Resources

Sign up to request clarification or add additional context in comments.

5 Comments

@Arthur Thanks. Do you see/know any better approach? What the OP wants looks very exotic to me.
Your solution sounds good. But if he want an exotic mapping, he should use a lot of wrappers @Embeddable classes. I hope he provide some information about your approach.
When i said A lot of relationships i refer to the mapping provided by @Maddy.Shik :)
Thanks for solution. As u suggested approach i am following is little exotic and nested collection is also not possible with hibernate. You mentioned to use Entity instead of list, that is possible only if i use Class corresponding to mapping table which doesn't seem in accordance with coding principles. Can u please suggest your approach?
Java Map will not allow non unique key. So only one course-teacher pair can be retrieved which will not fit my requirement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.