alin
alin

Reputation: 145

Cannot delete data from a table using hibernate

I tried many methods on the net, but it doesn't work. I want to delete data from a database using hibernate, but I get this errors SEVERE: Cannot delete or update a parent row: a foreign key constraint fails (sakila.comanda, CONSTRAINT comanda_ibfk_1 FOREIGN KEY (IDPRODUS) REFERENCES produs (IDPRODUS)) SEVERE: Could not synchronize database state with session

comanda means order and produs means product

Here is the code:

    private void StergeButtonActionPerformed(java.awt.event.ActionEvent evt) {
    try{
        org.hibernate.Transaction tx = session.beginTransaction();

        int idprodus = ((Produs)IdProdusComboBox.getSelectedItem()).getIdprodus();
        Produs produs = (Produs) session.get(Produs.class, idprodus);

        session.delete(produs);

        tx.commit();
    }catch(Exception e){
        System.out.println(e.getMessage());
    }
}

Upvotes: 0

Views: 936

Answers (1)

JB Nizet
JB Nizet

Reputation: 692231

This just means that deleting the product is impossible, because it would break a foreign key constraint in database. You have orders for your product, but you're trying to delete the product. How will you honor the orders? You have to decide:

  • either you delete the orders referencing the product before deleting the product
  • or you keep the orders in the database, but these orders must not reference the product anymore.

Not doing any of the above would leave the database in an inconsistent state: orders for products which don't exist. The foreign key constraint in the database ensures that such an inconsistent state is impossible.

Upvotes: 2

Related Questions