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 Customer
and class Job
. My application is for a fictious company that completes jobs for customers. My current implementation is so that the Job
class doesn't have anything to do with the Customer
class, there is no reference to it at all. The Customer
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 Job
has been done? I've only found this article that's relevant: http://www.ibm.com/developerworks/webservices/library/ws-tip-objrel3/index.html.
According to the implementation of the author, I would let the Job
constructor take a Customer
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.
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) {
children.add(child);
}
void removeChild(Child) {
children.remove(child);
}
}
class Child {
private Parent parent;
public void setParent(Parent parent){
if (this.parent != null)
this.parent.removeChild(this);
this.parent = parent;
this.parent.addChild(this);
}
}
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.