File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes OO, Patterns, UML and Refactoring and the fly likes many to many Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "many to many" Watch "many to many" New topic

many to many

Nawar Gailani
Ranch Hand

Joined: Feb 08, 2005
Posts: 46
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

Joined: May 26, 2003
Posts: 32811

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.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Joel McNary

Joined: Aug 20, 2001
Posts: 1824

...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.

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Nawar Gailani
Ranch Hand

Joined: Feb 08, 2005
Posts: 46
Yes, I thought the second is the correct. Thanks Jeanne.
Sorry about the posting in the wrong forum or section.
Yes, I already did the linking table, but I didn't mentioned it for simplicity. Thanks Joel for your time explaining with code.
I agree. Here's the link:
subject: many to many
It's not a secret anymore!