views:

711

answers:

2

I've got a one-to-one relation between a dealer and a seller which should be lazy using a proxy. For the side on which the foreign key is defined (the seller, references the dealer), this works fine. But it doesn't work from the other side - the seller is always loaded eagerly. I set constrained="true" as described in "Some explanations on lazy loading", but that didn't help.

Following is the used mapping:

<class name="Role" table="PER_PERSROLE" abstract="true">
 <id column="OID" type="long">
  <generator class="native" />
 </id>
 <discriminator column="SUBTYPE" type="string" />
</class>

<subclass name="Dealer" extends="Role" discriminator-value="DEAL">
 <property name="gpNr" column="GP_NR" type="string" />
 <one-to-one name="seller" property-ref="dealer" lazy="proxy" constrained="true"
  outer-join="false" />
</subclass>

<subclass name="Seller" extends="Role" discriminator-value="SELL">
 <many-to-one name="dealer" column="SELLER_DEALEROID" lazy="proxy"
  outer-join="false" />
</subclass>

Is it a problem that both classes reside in one table? I see that strictly speaking the relation isn't constrained on the database (it can't using this model), but the domain model always needs both entities and the application ensures this.

A: 

I'm guessing you are loading session.get(id)? Have you tried load the instance using an HQL query? That will allow you to specify in the query which relationships to eager or lazy load.

HTH

Tom
Hi Tom, I tried load(), get() and an HQL query. I'm not aware of a way to explicitly tell Hibernate to lazy load using an HQL query - I just know of 'join fetch ...' to eagerly load a relation even if it's lazy.
rudolfson
A: 

I think that the page you linked to explained it best, though I am not sure why it recommends setting constrained="true". If you think about it on the database level, Hibernate can't tell if the given property (the Dealer's seller) should be null or not without hitting the database (it needs to do a SELECT ... WHERE OID=:sellerOrDealerId to see if any rows are returned). And while it's hitting the database, it might as well fetch the rest of the row. From the other side of the association (Seller's dealer), there are no such problems since it has already fetched the row (and thus the SELLER_DEALEROID column).

I did encounter something similar to this once and was able to solve it by making the association non-optional (err, non-nullable)

Adam Batkin
But to make the association non-optional/non-nullable you have to set constrained to true. At least that's how I understand the description. Or how did you accomplished this?
rudolfson