• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

many to many

 
Nawar Gailani
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,
If I have many to many relation, how can I map this in Java?
For example, i have students and courses, every student may have one or more courses, and every course may have one or more students.
When I write a class represent student, I write it this way?
class Student {
private String name;
private Course course;
......
}

or like this?
class Student {
private String name;
private Vector courses;
......
}

The second seems more logical to me when I search for a specific student, but I don't know if I'm missing something!

Thanks in advance
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34695
367
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nawar,
You would need the second one as a student can be in multiple courses. If the course needs to know who is registered, it would need to have a Collection of students.

I'm moving this to our OO forum since it is about modeling Java rather than databases.
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...But it could be about modeling either!

Typically, in the database, there is a cross-relation table (which can be invisible to the object model) So your database structure would be something like:



While the code could look something like:

(Accessors left out as an exercise for the user.)

Note that student has a courseList and course has a studentList.
 
Nawar Gailani
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeanne:
Yes, I thought the second is the correct. Thanks Jeanne.
Sorry about the posting in the wrong forum or section.
Joel:
Yes, I already did the linking table, but I didn't mentioned it for simplicity. Thanks Joel for your time explaining with code.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic