I try to write my first DAO program. In my database, I created two tables : PROJECT and MILESTONE. Normally, I have an aggregation relationship between the project and the milestone : a project can have many milestones but a milestone is inevitably affected to only ONE project.
I have two main questions :
1) In the SQL tables, does it mean that I had to add a constrain (foreign key) on the projectid and relate that foreign key to the milestone table? So far, I choose to have a column named "projectid" in milestone table. In my opinion, it's simple if we do that.
2) When I create a milestone object, it's COMPULSORY to specifiy the projectid, so I tried to write this constructor :
public Milestone (String name, String description, String projectId) throws SQLException, ClassNotFoundException {
this.name = name;
this.description = description;
ProjectDAOImpl proj = new ProjectDAOImpl();
// "proj.findById(projectId)" is to verify if a real project exist having the specified id
if ( (proj.findById(projectId))!= null ) {
this.projectId = projectId;
}
else {
return null; //is it correct to do that in a constructor??
}
}
The probleme here is I don't know how can I translate this condition in Java : " If there is an existing project with this specified ID then the milestone will be affected to this project. If not, the milestone object will not be created". I mean how can I tell to the constructor to not create the object if there is no corresponding project?