NHibernate:延迟加载IUserType

时间:2011-09-02 16:00:16

标签: hibernate nhibernate lazy-loading

假设我们有一个存储客户详细信息的系统,以及一个存储员工详细信息的系统(假设情况!)。当EmployeeSystem访问Employee时,使用WCF从ClientSystem访问客户端信息,以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中实现延迟加载,或者我错过了什么?

1 个答案:

答案 0 :(得分:0)

这是一对一的关系吗?由于hibernate文档表明这一切都是可能的,因此xml配置文件中似乎有一些选项可以为一对一关系启用延迟加载,但它们显然没有效果。

one-to-one lazy association