在我的Postgres数据库中,我有一个organisation
表。CCD_ 2和CCD_。employee
表本身有一个phone_number
子表,依此类推
我需要删除一个组织,因此被删除组织的员工也需要删除,这些员工的电话号码也需要删除。
实现这一点的明显方法是使用一系列SQL语句
-- delete the organisation with ID 4
delete from phone_number where employee_id in (
select id from employee where organisation_id = 4
)
delete from employee where organisation_id = 4
delete from organisation where id = 4
当只涉及3个表时,这很好,但实际上还有更多的表,而且随着模式的变化,管理起来也变得困难。
另一个选项是打开所有外键的删除级联,例如在员工表中,将组织外键定义为
create table employee
(
organisation_id varchar(255) not null
constraint fk_organisation_employee
references organisation
on delete cascade
-- remainder of table definition omitted
);
如果我们对所有相关的外键都这样做,那么删除一个组织应该级联到直系子表,然后级联到直系子女的子女,以此类推。
然而,永久启用这种级联删除有点可怕。理想情况下,我希望在组织被删除时启用它,但这似乎是不可能的。
有问题的应用程序是一个Java应用程序,它使用Hibernate/JPA实现持久性。JPA具有支持自动删除子实体的功能,所以与其在数据库级别启用级联删除,不如利用这些功能?
这些方法中的一种比其他方法更好吗?还是还有另一种我没有考虑过的选择?
如果您想要一个允许您单独指定删除图的解决方案,请查看Blaze Persistence Entity Views,它可以让您做到这一点。除此之外,它还将更快一点,因为它将在一条语句中执行所有删除。