This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
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
Author

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
Marshal

Joined: May 26, 2003
Posts: 30586
    
154

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.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1817

...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
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: many to many