错误:
org.postgresql.util.PSQLException: ERROR: insert or update on table "food_order" violates foreign key constraint "food_order_invoice_id_fkey"
Detail: Key (invoice_id)=(2) is not present in table "invoice".
首先,我将数据插入发票表,然后将其ID插入另一个ID作为参考。我希望这些语句按顺序执行。
这是我的代码:
public static void insertInvoice(Invoice invoice) throws SQLException {
Connection connection = DatabaseConnectionPostgre.connection();
Statement statement = connection.createStatement();
PaymentType paymentType = invoice.getPaymentType();
String query = null;
switch (paymentType){
case Cash:
query = "insert into cash_invoice values(" +
"'" + invoice.getId() + "', " +
"'" + invoice.getDate() + "', " +
"'" + invoice.getTotalPrice() + "', " +
"'" + invoice.getCustomer().getId() + "', " +
"'" + invoice.getInvoiceStatus() + "', " +
"'" + ((CashInvoice) invoice).getDeliveryFee() + "' " +
")";
break;
case Cashless:
query = "insert into cash_invoice values(" +
"'" + invoice.getId() + "', " +
"'" + invoice.getDate() + "', " +
"'" + invoice.getTotalPrice() + "', " +
"'" + invoice.getCustomer().getId() + "', " +
"'" + invoice.getInvoiceStatus() + "', " +
"'" + ((CashlessInvoice) invoice).getPromo() + "' " +
")";
break;
}
statement.executeUpdate(query);
for (Food food:
invoice.getFoods()) {
query = "insert into food_order( food_id, invoice_id) values(" +
"'" + food.getId() + "', " +
"'" + invoice.getId() + "' " +
")";
statement.execute(query);
}
statement.close();
connection.close();
}