【问题标题】:Java insert data into database with Foreign KeyJava使用外键将数据插入数据库
【发布时间】:2015-12-10 17:30:10
【问题描述】:

所以我正在为需要能够将球队添加到数据库的足球组织创建一个小型应用程序。

我的数据库有以下 ERD:

我有以下代码可以将团队添加到我的数据库中:

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);
    }

}

必须可以在没有教练的情况下添加团队。 像这样:

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

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

Trainer_id 是一个 int,因为我还没有定义 trainer_id。 trainer_id 成为 int 的默认值,0。

但是我得到一个外键异常,因为数据库正在寻找一个 id 为 0 的培训师。

我该如何克服这个问题?

如何将我的 int 初始化为“null”?

【问题讨论】:

    标签: java database foreign-keys


    【解决方案1】:

    使用statement.setNull(3, java.sql.Types.INTEGER); 或将语句构造为insert into ploeg (naam, niveau) values(?,?),因此trainer_id 将默认为NULL

    【讨论】:

      【解决方案2】:

      在 POJO 方面,训练者 ID 应该是 java.lang.Integer,而不是原始的 int,以便允许 nulls。在 JDBC 方面,您可以使用setObject 而不是setInt,后者确实接受nulls:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-03
        • 1970-01-01
        • 2021-02-09
        • 1970-01-01
        相关资源
        最近更新 更多