I've a doubt regarding many to many and one to many mapping. Should we use Collection in both the classes in case of many to many mapping? or is it enough to use collection only in one class?
Let's take an example of many to many mapping, we have 2 tables "student" and "course". A Student can choose many courses and also, A Course can be chosen by many students. So my question is that should we use collection in both the classes (Student & Course) or is it enough to use Collection only in one class (i.e. Student) ?
Now let's take an example of one to many mapping, we have 2 tables "student" and "course". A student can choose many courses, but a particular Course is chosen by only one student. And each course is uniquely identified by course_id (unique). Then it means course_id can't be duplicated, it clearly mean that we use only "Set" (duplicacy is not allowed in Set). So conclusion is that we can not use "List" in case of one to many mapping.
Please someone explain these 2 scenarios. I'm confused, please help me out !!
Ignore ORM, databases, mapping and all that, and ask yourself 2 questions:
- 1) "Is there any use case in my application where given a Student, it should return back list of Courses?"
If yes, then your Student should hold a collection of Courses. If no, it need not.
The use case could be a straightforward one like "allow user to select a Student and see their enrolled Courses",
or it could be something to do with report creation by an admin.
- 2) similarly, "Is there any use case in my application where given a Course, it should return back list of Students?"
If yes, then your Course should hold a collection of enrolled Students. If no, it need not.
Once those questions are answered, you can think about which data structure interface and data structure implementation to use
to represent those relationships.
Use a List if sequence is important. Use a Set if sequence doesn't matter. Use SortedSet if entries should be in some sorted order.
Use a Map if some kind of key is maintained. Use Collection if it can contain duplicates and sequence does not matter.
Once the data structure is decided, represent it appropriately in mapping file using <set>, <bag>, <map>, or <list>.
subject: Hibernate - many to many and one to many mapping