nhibernate - 使用property-ref映射到非关键字段时,延迟加载不适用于多对一关系

标签 nhibernate lazy-loading icriteria

我有一个使用NHibernate映射的旧数据库。关注的对象是“帐户”和“通知”对象列表。对象看起来像:

public class Notification
{
    public virtual int Id { get; set; }
    public virtual DateTime BatchDate { get; set; }
    /* other properties */

    public virtual Account Account { get; set; }
}

public class Account 
{
    public virtual int Id { get; set; }
    public virtual string AccountNumber { get; set; }
    /* other properties */ 
}


映射文件如下所示:

<class name="Account" table="Account" dynamic-update="true">
<id name="Id" column="AccountID">
    <generator class="native" />
</id>
<property name="AccountNumber" length="15" not-null="true" />
    <!-- other properties -->
</class>

<class name="Notification" table="Notification">
    <id name="Id" column="Id">
        <generator class="native" />
    </id>
    <!-- other properties -->
    <many-to-one name="Account" class="Account" property-ref="AccountNumber" lazy="proxy">
        <column name="AcctNum" />
    </many-to-one>


但是,当我创建诸如

return session.CreateCriteria(typeof(Notification)).List<Notification>();


我收到Select N + 1的情况,即使从未引用过该帐户,每个帐户都已加载。当多对一映射为惰性代理时,为什么所有帐户都被加载?

最佳答案

此问题是由property-ref属性引起的。延迟加载仅在many-to-one引用正在使用另一个对象的主键时起作用,因为NHibernate假定存在一个外键约束来强制这种值的有效性。使用非主键(由property-ref指示)时,NHibernate不会进行此假设,因此不会假设相关对象必须存在。由于它不想为不存在的对象创建代理(即应为null而不是代理),因此它急切地获取远程对象。当指定not-found="ignore"时,存在相同的问题,因为这表明未强制使用外键关系,并可能导致空引用。

也可以看看:


NHibernate creates proxy via session.Load(), but not via Linq or Criteria API
http://frankmao.com/2007/12/05/lazy-load-conflicts-with-property-ref-in-many-to-one-mapping/

关于nhibernate - 使用property-ref映射到非关键字段时,延迟加载不适用于多对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/604373/

相关文章:

nhibernate - NHibernate用于企业应用程序?

"virtual"模式下的 WPF 文本框

javascript - 单元测试 AngularJS 延迟加载 Controller

java - 从依赖对象列表中更新一个值

nhibernate - 一级缓存可以与 ICriteria 或其他 API 一起使用吗?

NHibernate 标准 - 如何过滤属性组合

nhibernate - 与 NHibernate ICriteria/QueryOver 查询的外连接中的条件相等

c# - Nhibernate GetById 返回 ObjectNotFoundException insetad of null

NHibernate 自定义集合类型

hibernate - 臭名昭著的: Invalid index n for this SqlParameterCollection with Count=