Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate: how to enable lazy loading on one-to-one mapping

One-to-one relations within nhibernate can be lazyloaded either "false" or "proxy". I was wondering if anyone knows a way to do a lazy one-to-one mapping.

I worked out a hack to achieve the same result by using a lazy set mapped to a private field, and having the public property return the first result of that set. It works, but isn't the cleanest code...

Thanks in advance!

like image 657
Casper Avatar asked Dec 23 '08 14:12

Casper


3 Answers

Lazy loading of one-to-one isn't supported unless the association is mandatory. See here for the reasoning.

It boils down to the fact that in order to decide if the other side of the relationship exists (N)Hibernate has to go to the database. Since you've already taken the database hit, you might as well load the full object.

While there are cases where hitting the DB just to see if the related object exists without actually loading the object makes sense (if the related object is very "heavy"), it isn't currently supported in NHibernate.

like image 102
Sean Carpenter Avatar answered Sep 19 '22 11:09

Sean Carpenter


As far as I know, there isn't a non-hacky way to lazy load a one-to-one. I hope I'm wrong, but last time I checked it was the case.

like image 22
James Gregory Avatar answered Sep 18 '22 11:09

James Gregory


There is way thought. It's described here in details :

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernateTest" namespace="NHibernateTest">
  <class name="Person" >
    <id name="PersonID" type="Int32">
      <generator class="identity" />
    </id>
    <property name="LastName" type="String" length="50" />
    <property name="FirstName" type="String" length="50" />
    <many-to-one name="Photo" class="PersonPhoto" />
  </class>

  <class name="PersonPhoto">
    <id name="PersonID" type="Int32">
      <generator class="foreign">
        <param name="property">Owner</param>
      </generator>
    </id>
    <property name="Photo" type="BinaryBlob" />
    <one-to-one name="Owner" class="Person" constrained="true" />
  </class>
</hibernate-mapping> 
like image 39
Artem Tikhomirov Avatar answered Sep 21 '22 11:09

Artem Tikhomirov