Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Web services programming tips and tricks: Implementing many-to-many object relationships

Using collections to manage many-to-many object relationships

Scott W. Ambler (scott_ambler@ca.ibm.com), Practice Leader, Agile Development, Rational Methods Group, IBM
Scott W. Ambler is President of Ronin International, a consulting firm specializing in object-oriented software process mentoring, architectural modeling, and Enterprise JavaBeans (EJB) development. He has authored or co-authored several books about object-oriented development, including the recently released The Object Primer 2nd Edition, which covers, in detail, the subjects summarized in this article. He can be reached at scott.ambler@ronin-intl.com and at his Web site at www.ambysoft.com.

Summary:  In Java, a many-to-many object relationship is implemented via a combination of collections and operations to manipulate those collections.

Date:  15 Mar 2001
Level:  Introductory
Also available in:   Japanese

Activity:  5726 views
Comments:  

Relationships -- when I use the term relationship, I mean the Unified Modeling Language (UML) concepts of association, aggregration, and composition -- are implemented via the combination of attributes and methods (operations). The attributes describe the relationship, and the methods define and update the relationship. In An overview of relationships, I discussed the fundamentals of object relationships. We have described implementation strategies in both Implementing object relationships with a singular multiplicity and Implementing one-to-many object relationships. Now I would like to describe how to implement a bidirectional many-to-many relationship.

A many-to-many relationship is one that has multiplicities of many -- one of 0..*, 1..*, 0..n, or 1..n where n is a number > 1 -- at both ends of the relationship. For example, in Figure 1 you see that there is a many-to-many relationship, "instructs", between the Professor and Seminar classes. There is also a one-to-many association, "oversees", between these two classes.


Figure 1: The Professor and Seminar classes
Professor and Seminar classes

Implementing the relationship

Many-to-many relationships require the most amount of work to implement because each object involved in the relationship must maintain a collection of references to the other objects to which it is related. You saw in Implementing one-to-many object relationships how to implement the many sides of an association via the use of a collection class (in that case I used a HashSet), a getter and setter for the collection, and operations to insert and remove items from the collection. When using a many-to-many association you merely need to do this in both classes.

Listing 1 presents the scaffolding code in the Professor class to manage its part of the "instructs" association with instances of Seminar. Listing 2 presents the similar code for the Seminar class to manage its part of the association. I didn't include the header documentation or the source code for the accessors for the sake of brevity.

Notice how, in Listing 1, the addSeminar(seminar) method automatically invokes addInstructor(professor) in the Seminar class and, in Listing 2, this method does the same thing in the other direction. This code is robust because it automates the management of the association in both directions, reducing the chance of introducing a logic error in your code.


Listing 1. Managing the association from a Professor to the Seminars he/she instructs

private HashSet seminars;

public void addSeminar(Seminar seminar)
{
    //  If the seminar is not already in the collection add it
    //  The if statement avoids an infinite loop managing the association
    if ( ! getSeminars().contains(seminar)) {
        getSeminars().add(seminar);

        //  The Seminar should know who instructs it
        seminar.addInstructor(this);
     }
}

public void removeSeminar(Seminar seminar)
{
   //  Only perform the removal of the seminar if it is in the collection
   //  The if statement avoids an infinite loop managing the association
   if ( getSeminars().contains(seminar)) {
    //  Remove the seminar from the collection
       getSeminars().remove(seminar);

  // Update the seminar so that it knows that the professor no longer instructs it
       seminar.removeInstructor(this);
    }
}




Listing 2. Managing the association from a Seminar to the Professors who teach it

private Vector instructors;

public void addInstructor(Professor professor)
{
    //  If the professor does not exist in the collection add it
    //  The if statement avoids an infinite loop managing the association
    if ( ! instructors.contains( professor )) {
        getInstructors().add( professor );

        // Update the other end of the association
        professor.addSeminar( this );
    }
}

public void removeInstructor(Professor professor)
{
    if ( instructors.contains( professor )) {
       getInstructors().remove( professor );

       // Update the other end of the association
       professor.removeSeminar( this );
    }
}



Adhering to coding conventions

Also notice the use of whitespace in the parameter list of method invocations in Listing 2, as compared to Listing 1. Both styles are fine, just pick one and follow it consistently in your code. If you're interested in Java coding style conventions, I highly recommend the book The Elements of Java Style (see Resources).


Resources

About the author

Scott W. Ambler is President of Ronin International, a consulting firm specializing in object-oriented software process mentoring, architectural modeling, and Enterprise JavaBeans (EJB) development. He has authored or co-authored several books about object-oriented development, including the recently released The Object Primer 2nd Edition, which covers, in detail, the subjects summarized in this article. He can be reached at scott.ambler@ronin-intl.com and at his Web site at www.ambysoft.com.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=SOA and Web services, Java technology
ArticleID=11501
ArticleTitle=Web services programming tips and tricks: Implementing many-to-many object relationships
publish-date=03152001
author1-email=scott_ambler@ca.ibm.com
author1-email-cc=

Next steps from IBM

Rational Modeler is a free, UML 2.1 based environment that helps users to improve communication by specifying, visualizing and documenting their system, architecture and software designs using a standard graphical language.


Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

For articles in technology zones (such as Java technology, Linux, Open source, XML), Popular tags shows the top tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), Popular tags shows the top tags for just that product zone.

For articles in technology zones (such as Java technology, Linux, Open source, XML), My tags shows your tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), My tags shows your tags for just that product zone.

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Try IBM PureSystems. No charge.

Special offers