2014-05-16 74 views
1

我使用的是NHibernate 3.3.3.4001。我有一個問題,在發出Get請求時,NHibernate不會延遲加載數據。相反,它會填充整個對象模型,導致性能非常低下。該.hbm文件如下:NHibernate不懶加載

<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
        assembly="My.Assembly" namespace="Assembly.Model"> 

    <class name="Parent" table="tblParent"> 
    <id name="ID"> 
     <generator class="native"></generator> 
    </id> 
    <version name="Version" column="Version"/>  
    <component name="Children"> 
     <bag name="Collection" table="tblChildren" 
          cascade="save-update, merge" inverse="true"> 
     <key column="ParentID"></key> 
     <one-to-many class="Children"></one-to-many> 
     </bag> 
    </component> 
    <property name="DateCreated" column="DateCreated" update="false" insert="false" /> 
    <property name="Inactive" column="Inactive" /> 
    </class> 

</hibernate-mapping> 

我所預料的NHibernate加載所有子對象懶洋洋地,而不是發送查詢到數據庫。我曾嘗試添加明確的lazy = truedefault-lazy=true,但它沒有區別。我檢查了Config對象,可以看到映射有islazy=true

我打電話找如下:

using (var transaction = Session.BeginTransaction()) 
{ 
    t = Session.Get<T>(id); 
    transaction.Commit(); 
} 

我困惑的是爲什麼這不加載懶洋洋的,但查詢所有子對象的數據庫?

回答

1

不知道我是否理解你的真正目標。上面代碼片段中組件的內容是否完整?或者它只是一個縮短的版本?

無論如何,這裏所說:5.1.13. component, dynamic-component(引用)

<component>元素映射一個孩子的性能對象到父類的表列....

因此,背後的想法主要是將它用作C#透視圖中的引用對象,而將beeing存儲在一個表中。這個例子7.1. Dependent objects

<class name="Eg.Person, Eg" table="person"> 
    <id name="Key" column="pid" type="string"> 
     <generator class="uuid.hex"/> 
    </id> 
    <property name="Birthday" type="date"/> 
    <component name="Name" class="Eg.Name, Eg"> 
     <parent name="NamedPerson"/> <!-- reference back to the Person --> 
     <property name="Initial"/> 
     <property name="First"/> 
     <property name="Last"/> 
    </component> 
</class> 

因爲實體是這樣的:

public class Person 
{ 
    ... 
    public virtual Name Name { get; set; } 

public class Name 
{ 
    public virtual Person NamedPerson { get; set; } 
    public virtual string Initial { get; set; }  
    ... 

所以,如果你的情況,兒童<component>其實只是一個集合 - 不使用上述映射,但像這樣的東西:

家長:

<class name="Parent" table="tblParent"> 
    <id name="ID" generator="native" /> 
    <version name="Version" column="Version"/>  

    <!-- just a bag --> 
    <bag name="Children" table="tblChildren" cascade="save-update, merge" inverse="true"> 
    <key column="ParentID"></key> 
    <one-to-many class="Child"></one-to-many> 
    </bag> 

    <property ... 
</class> 

兒童:

<class name="Child" table="tblChildren"> 
    ... 
    <many-to-one name="Parent" column="ParentID" /> 
    ... 

和C#:

public class Parent 
{ 
    public virtual IList<Child> Children { get; set; } 
    ... 

public class Child 
{ 
    public virtual Parent Parent { get; set; } 
    ... 

而且所有的裝載肯定會偷懶

+0

謝謝,這讓我走上了正軌。主要問題是''嵌套在'' – user2984303

+0

對,很高興看到這一點。享受NHibernate,偉大的工具;) –

0

您正在嘗試加載組件的集合。我不認爲可以懶惰地加載它們。嘗試將您的組件轉換爲第一類實體。