18

我有一个使用 NHibernate 映射的遗留数据库。关注的对象是一个 Account 和一个 Notification 对象列表。对象看起来像:

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 案例,其中每个帐户都被加载,即使该帐户从未被引用。当多对一映射为惰性代理时,为什么所有帐户都被加载?

4

1 回答 1

15

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

也可以看看:

于 2010-09-30T16:11:32.870 回答