【问题标题】:Hibernate : delete parent not referenced by childrenHibernate:删除未由子级引用的父级
【发布时间】:2012-04-16 11:02:41
【问题描述】:

当没有孩子引用它时,我需要删除它。这在 Hibernate 中可能吗? (实际上我使用的是流利的 nhibernate,但我认为答案是一样的)

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

与正常的亲子关系不同,我不会有意识地选择删除公司。就用户而言,他只是在删除一个客户;删除未引用的公司只是这样做的副产品。

【问题讨论】:

    标签: hibernate nhibernate orm fluent-nhibernate


    【解决方案1】:

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

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

    【讨论】:

    • @Andy:此外,“公司”可能还有其他链接,例如“建筑”。如果您想删除“公司”,您也应该手动断开此类链接。
    【解决方案2】:

    我不知道通过 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();
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-02
      • 2015-08-15
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 2013-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多