I've got two tables, "Person" and "User". Every person has one and only one (not zero nor two, butONE) user associated. But there coud be a user with no person associated. Whenever I'm retrieving a person from the database, it's probable I'd be needing the user, too. This is true the other way around: If I retrieve a User, I'm probably be needing the person, too. So I want NHibernate to fetch this two entities all at once, with an outer join. There are times I fetch this two entities by the user, and times I fetch them by the person.
So I wrote this mappings:
Code:
<class name="Rules.Person, Rules" table="Person">
<id name="Id" type="Int32" unsaved-value="0">
<column name="id" />
<generator class="native" />
</id>
<many-to-one name="User" class="Rules.Usuario, Rules" fetch="join" cascade="save-update" unique="true">
<column name="id_user" not-null="true" unique="true"/>
</many-to-one>
...
Code:
<class name="Rules.User, Rules" table="User">
<id name="Id" type="Int32" unsaved-value="0">
<column name="id" />
<generator class="native" />
</id>
<one-to-one name="Person" constrained="false" outer-join="true" fetch="join" property-ref="User"/>
...
everything is working fine, but I was looking at the generated SQL, and I found out that as soon as I select the User, this SQLs are fired:
Code:
SELECT user0_.id AS id2_, user0_.nick AS nick2_,
person1_.id AS id0_, person1_.person1_.apellido AS apellido0_,
person1_.id_user AS id_user0_
FROM user AS user0_ LEFT OUTER JOIN person AS person1_ ON user0_.id = person1_.id_user
WHERE user0_.id=@p0
...
(some more sql for other properties not shown)
...
Code:
SELECT person0_.id AS id2_, person0_.apellido AS apellido2_,
person0_.id_user AS id_user2_,
user1_.id AS id1_, user1_.nick AS nick1_
FROM person AS person0_ LEFT OUTER JOIN Prestamos.dbo.user user1_ on person0_.id_user=user1_.id
WHERE person0_.id_user=@p0
so, it's fetching the same data two times... once when retrieving v_user.Person and then retrieving v_user.Person.User.
Is there a way I can avoid this? perhaps the mapping should be changed, or something?
Alejandro.