2011-09-02 66 views
1

假設我們有一個存儲客戶細節的系統和一個存儲員工細節的系統(假設情況!)。當EmployeeSystem訪問員工,客戶信息是從使用WCF的ClientSystem訪問,在IUserType實施:NHibernate:延遲加載IUserType

NHibernate的映射:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
    assembly="EmployeeSystem" namespace="EmployeeSystem.Entities"> 
    <class name="Employee" table="`Employee`" > 
     <id name="Id" column="`Id`" type="long"> 
     <generator class="native" /> 
     </id> 
     <property name="Name"/> 
     <property 
     name="Client" column="`ClientId`" 
     lazy="true" 
     type="EmployeeSystem.UserTypes.ClientUserType, EmployeeSystem" /> 
    </class> 
</hibernate-mapping> 

IUserType實現:

public class ClientUserType : IUserType 
{ 
    ... 

    public object NullSafeGet(IDataReader rs, string[] names, object owner) 
    { 
     object obj = NHibernateUtil.Int32.NullSafeGet(rs, names[0]); 

     IClientService clientService = new ClientServiceClient(); 
     ClientDto clientDto = null; 

     if (null != obj) 
     { 
      clientDto = clientService.GetClientById(Convert.ToInt64(obj)); 
     } 

     Client client = new Client 
     { 
      Id = clientDto.Id, 
      Name = clientDto.Name 
     }; 

     return client; 
    } 

    ... 

} 

即使我在該屬性上具有lazy =「true」,只要Employee被加載,它就會加載客戶端。這是正確的行爲?我是否必須在NullSafeGet中實現惰性加載,還是我錯過了某些東西?

+0

向我們展示如何加載員工。 – Dmitry

回答

0

這是一對一的關係嗎?由於hibernate文檔表明這是完全可能的,甚至似乎在xml配置文件中有一些選項可以打開一對一關係的延遲加載,但它們顯然沒有效果。

one-to-one lazy association

+0

嗯,這有點愚蠢,但我不能抱怨太多優秀的工具,畢竟它是免費的。如果客戶端的ID被訪問,我可能會考慮從NullsafeGet返回一個代理的方法,如果需要其他字段,則可以獲取實體。目前,我發現客戶端可以延遲加載,如果我加載()員工,而不是Get()。 –

+0

-1。首先一對一可以是懶惰的:http://community.jboss.org/wiki/Someexplanationsonlazyloadingone-to-one。其次,這不會解決OP問題,因爲他需要一個自定義加載(IUserType從WCF加載對象)。 – Dmitry