[英]Java insert data into database with Foreign Key
因此,我正在为足球组织创建一个小型应用程序,该应用程序需要能够将球队添加到数据库中。
我的数据库具有以下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是一个整数,因为我尚未定义trainer_id。 trainer_id成为int的默认值0。
但是随后我得到了一个外键异常,因为数据库正在查找ID为0的培训师。
我该如何克服?
如何将我的int初始化为“ null”?
使用statement.setNull(3, java.sql.Types.INTEGER);
或将语句构造为insert into ploeg (naam, niveau) values(?,?)
的语句,因此trainer_id
将默认为NULL
。
在POJO方面,培训师ID应该是java.lang.Integer
,而不是原始int
,以允许使用null
。 在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.