简体   繁体   中英

Aggregation relationship in JAVA (DAO) and SQL

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?

  1. Constructor can not return value. You can throw an exception (eg. IllegalArgumentException) instead of returning the null value.

First of all the constructor cannot return anything. Plus you can give an exception...probably a valid exception within the constructor

try this link and make changes accordingly Is it good practice to make the constructor throw an exception?

@AutoWired
ProjectDAOImpl proj;

public Milestone (String name, String description, Integer projectId){
 this.name = name;
 this.description = description;
 if ( (proj.findById(projectId))!= null ) throws NullPointException
}

Use Integer datatype for ids like projectId and you should Autowire Dao classes IF the Dao class has to be called many times throughout the class.

And regarding the first question i think your databse tables should probably look like this for the scenario you mentioned.

Project

projectId (PK),
// ...other fields

Milestone

milestoneId (PK),
projectId (FK),
// ...other fields

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM