Exception in deletion of Entity with Composition

I have master-detail composition entities that I am trying to delete programmatically but getting the following exception.

PSQLException: ERROR: update or delete on table "erp_plan_order" violates foreign key constraint "fk_erp_plan_order_line_on_plan_order" on table "erp_plan_order_line" Detail: Key (id)=(fbd75c37-7f4b-e5bd-add1-e7eab75b2b63) is still referenced from table "erp_plan_order_line".

In the Parent entity structure (PlanOrder), CASCADE DELETE:

 @Composition
@OnDelete(DeletePolicy.CASCADE)
@OneToMany(mappedBy = "planOrder")
protected List<PlanOrderLine> planOrderLine;

Why I am getting exception, thanks for any help.

Hi Mortoza,

Probably your entities are not soft-deleted. In this case, the @OnDelete annotation affects only the generation of foreign key constraints for cascading on the database level. Check if the FK constraint has the on delete cascade clause.

Hi Konstantin
Thanks. Can I check it from Studio, thanks for helping on how!

You cannot see it in Studio, only in the 20.create-db.sql script in your project and directly in the database.

For example, if you use Postgres, launch psql:

psql -U cuba -d mydb

Then run \d mytable command. You will see the table’s DDL, including the FK definitions like this:

Foreign-key constraints:
    "fk_debt_case_debtor_id" FOREIGN KEY (debtor_id) REFERENCES debt_debtor(id) ON DELETE CASCADE

Of course, any graphical tool like pgAdmin will also work.

Thank you Konstantin. I see in the database using pgAdmin as follows:

06%20PM
19%20PM

I didn’t touch any table create/modify manually, it was created through the Studio. How can will have it worked straight?

Now to fix the issue, please suggest what will be the step by step corrective measure!

  1. Drop the constraint and create it again with “ON DELETE CASCADE” option. See Postgres docs for how to define constraints.

  2. Open your 20.create-db.sql file, check and fix the constraint if needed.