• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

many to many

 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author & internet detective
Posts: 41860
908
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 1844
Eclipse IDE Ruby Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic