MarioDS MarioDS - 1 year ago 85
Java Question

Programming a one-to-many relationship

So I am surprised that doing a search on google and stackoverflow doesn't return more results.

In OO programming (I'm using java), how do you correctly implement a one-to-many relationship?

I have a class

and class
. My application is for a fictious company that completes jobs for customers. My current implementation is so that the
class doesn't have anything to do with the
class, there is no reference to it at all. The
class uses a collection and methods to hold, retrieve and modify information about the Jobs that have been assigned by and/or completed for a customer.

The question is, what if I'd want to find out for which customer a particular
has been done? I've only found this article that's relevant:

According to the implementation of the author, I would let the
constructor take a
parameter, and store it so I can retrieve it. However, I see no guarantee at all that this model can be consistent. There are no restirctions to set the related customer for a job as a customer that the job was not for, and add jobs to customers that were done for someone else. Any help on this would be appreciated.

Answer Source

There's no 100% surefire way to maintain the integrity.

The approach which is usually taken is to use one method to construct the relationship, and construct the other direction in that same method. But, as you say, this doesn't keep anyone from messing with it.

The next step would be to make some of the methods package-accessible, so that at least code which has nothing to do with yours can't break it:

class Parent {

  private Collection<Child> children;

  //note the default accessibility modifiers
  void addChild(Child) {

  void removeChild(Child) {

class Child {

   private Parent parent;
   public void setParent(Parent parent){
     if (this.parent != null)
     this.parent = parent;

In reality, you won't often model this relationship in your classes. Instead, you will look up all children for a parent in some kind of repository.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download