Can I add 'ON DELETE CASCADE' to tables managed by Hibernate?

后端 未结 6 1748
不知归路
不知归路 2021-01-04 00:14

I have some tables managed by Hibernate with various foreign key constraints. Cascade on delete is currently managed by Hibernate alone. For playing around with test data I

6条回答
  •  情歌与酒
    2021-01-04 00:45

    I see two potential issues:

    1. If an entity that represents the table to which you cascade operations directly in the database is versioned, then it would not work because when Hibernate tries to delete records on its own, the version check would fail (Hibernate would assume concurrent thread already updated or deleted the corresponding records).
    2. If there are use cases in which your business logic re-persists such entity instances after removal has been cascaded to them from the parent (for example, you are deleting old parent and migrating associated children to a new one, although for better clarity I would not cascade removal at all if such a use case exists for an association, but it's up to you as it is allowed by the JPA spec), then Hibernate would just un-schedule the deletion of children and delete only the parent, so you would still end up with deleted children if you cascade deletion in the database.

    Probably there are some other situations that could be problematic in some scenarios, so I would recommend not to do it.

提交回复
热议问题