Video in progress
I get a foreign key error when deleting an entity. How do you correctly organize deleting the related records?
The options: put CascadeType.REMOVE/orphanRemoval on the children collection, use ON DELETE CASCADE in the database (@OnDelete in Hibernate), or delete the children first with a bulk query. The choice depends on the number of children and on whether you need Java logic on deletion.
📖 Answer
The error usually looks like this:
ERROR: update or delete on table "orders" violates foreign key constraint
"fk_order_item_order" on table "order_item"
That is, you're deleting an orders row while an order_item still references it.
- JPA cascade:
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrderItem> items = new ArrayList<>();
em.remove(order) first loads all the items and sends a separate DELETE for each. That's fine for 10 elements, and @PreRemove callbacks work too. For 50 thousand elements it's far too slow.
- At the database level:
@ManyToOne(fetch = FetchType.LAZY)
@OnDelete(action = OnDeleteAction.CASCADE)
private Order order;
In the migration, the FK is written with on delete cascade. Hibernate sends a single DELETE to orders and the database deletes the children itself. It's fast, but Hibernate doesn't know about children already loaded in the persistence context, and callbacks aren't called.
- By hand, with two bulk queries:
em.createQuery("delete from OrderItem i where i.order.id = :id").setParameter("id", id).executeUpdate();
em.createQuery("delete from Order o where o.id = :id").setParameter("id", id).executeUpdate();
One important question: do other tables reference the children too? Then the chain gets longer and the error shows up on the next table. Sometimes the right answer isn't deleting but setting the status to ARCHIVED.
And don't forget: don't put CascadeType.REMOVE on a @ManyToOne or @ManyToMany side, because deleting one child can delete the parent and the other children too.
Sign up to mark studied questions and save your progress.