【问题标题】:Nhibernate HiLo id values before commit提交前休眠 HiLo id 值
【发布时间】:2012-03-05 21:30:34
【问题描述】:

我正在开发一个应用程序,用户可以通过该应用程序发送带有附件的电子邮件。电子邮件和附件域对象都将 hilo 定义为 id 生成器,如下所示:

<id name="Id">
  <generator class="hilo" />
</id>

Nhibernate 使用名为 hibernate_unique_key 的表生成架构,其中包含 next_hi 列。

当用户向电子邮件添加附件时,应用程序内部会将附件对象添加到附件列表并将其绑定到网格视图,以便用户可以看到他们添加的内容。 可选地,用户可以选择以前添加的附件并通过单击删除按钮将其从列表中删除。 问题是,由于没有对象被保存到数据库,附件的 id 没有被分配,所以我不能唯一标识附件 obj 从列表中删除。

有没有办法在保存之前为对象分配 id 值?我想我不太了解 hilo 算法的用法及其主要目的。

【问题讨论】:

    标签: c# nhibernate


    【解决方案1】:

    使用HiLo 是为了分配标识符而无需往返数据库。你需要做的是这样的事情(你需要满足删除附件和异常处理等):

    private void CreateNewEmail_Click(object sender, EventArgs e)
    {
        // start a transaction so that all our objects are saved together.
        this.transaction = this.session.BeginTransaction();
        this.currentEmail = new Email();
    }
    
    private void AddAttachment_Click(object sender, EventArgs e)
    {
        var attachment = new Attachment();
        // set the properties.
    
        // Add it to the session so that the identifier is populated (no insert statements are sent at this point)
        this.session.Save(attachment);
    
        // Also add it to the email
        this.currentEmail.Attachments.Add(attachment);
    }
    
    private void SendEmail_Click(object sender, EventArgs e)
    {
        // Commit the transaction (at this point the insert statements will be sent to the database)
        this.transaction.Commit();
    }
    

    这里有几个链接也可以帮助您更好地理解 HiLo 和 NHibernate:

    http://ayende.com/blog/3915/nhibernate-avoid-identity-generator-when-possible

    http://nhforge.org/blogs/nhibernate/archive/2009/03/20/nhibernate-poid-generators-revealed.aspx

    【讨论】:

    • 他不能也做一个由 HiLo 算法生成的分配 ID 以防止多次往返吗?如果需要,这种策略会使添加多个附件变得难以批处理。
    • 我不确定我是否遵循,ID 将由 HiLo 算法生成并在调用 session.Save() 时由会话分配,但是此时没有发生数据库命中,这使得它非常适合批处理...
    • 我想如果他希望他的事务范围限定在用户操作上发生(我认为这是一种危险的模式),这会起作用。如果他将交易范围扩大到更高,则需要更多考虑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 2010-11-16
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    相关资源
    最近更新 更多