繁体   English   中英

休眠:删除子级未引用的父级

[英]Hibernate : delete parent not referenced by children

当没有子级引用它时,我需要删除一个父级。 在Hibernate中有可能吗? (实际上,我使用的是流利的nhibernate,但我想答案是相同的)

例如,我有许多来自不同公司的客户。 当我删除公司的最后一个客户时,我也要自动删除公司详细信息。

与正常的亲子关系不同,我没有自觉选择删除公司。 就用户而言,他只是删除一个客户; 删除未引用公司只是这的副产品。

Hibernate不会为您神奇地做到这一点。 您必须自己实施:

Company company = customer.getCompany();
company.removeCustomer(customer);
session.delete(customer);
if (company.getCustomers().isEmpty()) {
    session.delete(company);
}

我不知道通过NHibernate映射执行此操作的方法,您可能需要在删除客户逻辑中编写一些逻辑,该逻辑计算带有公司标识符的客户表中的记录数,而客户标识符不是一个被删除,如果结果计数为0,则删除客户和公司。

伪代码:

public void Delete(Customer customer)
{
    using (var transaction = session.BeginTransaction())
    {
        int remainingCustomers = 
            session.Query<Customer>(c => c.CompanyId == customer.CompanyId && c.CustomerId != customer.CustomerId).Count();

        session.Delete(customer);

        if (remainingCustomers == 0)
        {
            session.Delete(customer.Company);
        }

        transaction.Commit();
    }
}

另外,如果不需要立即删除,则可以按计划运行存储过程以“整理”旧公司。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM