简体   繁体   English

Java使用外键将数据插入数据库

[英]Java insert data into database with Foreign Key

So I am creating a small application for a football organisation that needs to be able to add teams to the database. 因此,我正在为足球组织创建一个小型应用程序,该应用程序需要能够将球队添加到数据库中。

My database has the following ERD: 我的数据库具有以下ERD:

数据库ERD

I have the following code to add teams to my database: 我有以下代码将团队添加到我的数据库中:

public void toevoegenPloeg(Ploeg ploeg) throws DBException, ApplicationException {
    //connectie tot stand brengen
    System.out.println(ploeg.getTrainerID());
    try (Connection connection = ConnectionManager.getConnection();) {
        //statement opstellen
        try (PreparedStatement statement = connection.prepareStatement("insert into ploeg (naam, niveau, trainer_id) values(?,?,?)");) {
            statement.setString(1, ploeg.getNaam());
            statement.setString(2, ploeg.getNiveau());
            statement.setInt(3, ploeg.getTrainerID());
            statement.execute();


        } catch (SQLException ex) {
            throw new DBException("SQL-exception in de toevoegenPloeg-methode - statement" + ex);
        }
    } catch (SQLException ex) {
        throw new DBException("SQL-exception in de toevoegenPloeg-methode - connectie " + ex);
    }

}

It has to be possible to add teams without a trainer. 必须有可能增加没有培训师的团队。 Like this: 像这样:

PloegTrans PT = new PloegTrans();
PersoonTrans PeT = new PersoonTrans();

Ploeg ploeg1 = new Ploeg();
ploeg1.setNiveau("U9");
PT.ploegToevoegen(ploeg1);

Trainer_id is an int and because I haven't defined the trainer_id. Trainer_id是一个整数,因为我尚未定义trainer_id。 The trainer_id becomes the default of an int, 0. trainer_id成为int的默认值0。

But then I get a Foreign Key exception, because the database looks for a trainer with id 0. 但是随后我得到了一个外键异常,因为数据库正在查找ID为0的培训师。

How can I overcome this? 我该如何克服?

How can I initialize my int as a "null"? 如何将我的int初始化为“ null”?

Use statement.setNull(3, java.sql.Types.INTEGER); 使用statement.setNull(3, java.sql.Types.INTEGER); or construct the statement as insert into ploeg (naam, niveau) values(?,?) , so trainer_id will default to NULL . 或将语句构造为insert into ploeg (naam, niveau) values(?,?)的语句,因此trainer_id将默认为NULL

On the POJO's side, the trainer ID should be a java.lang.Integer , not a primitive int , in order to allow null s. 在POJO方面,培训师ID应该是java.lang.Integer ,而不是原始int ,以允许使用null On the JDBC side, you could use setObject instead of setInt , which does accept null s: 在JDBC方面,可以使用setObject代替setInt ,后者不接受null

// getTrainerID() returns either an Integer instance or null
statement.setObject(3, ploeg.getTrainerID()); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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