在其他语句之前顺序执行Java sql语句

时间:2020-05-08 14:06:44

标签: java postgresql jdbc

错误:

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

0 个答案:

没有答案