Hibernate version:
3.1.3 (but I checked the source and it's the same for 3.2.1)
In our code, we have many one-to-one relationships like the one below between Person and User. We found that whenever a Person object was loaded Hibernate always loaded the corresponding User object from the database (expected behavior) and did not load the User object from the second level cache (unexpected behavior).
In looking at the way that the one-to-one relationships are cached in the OneToOneType.java, it did not put the ID of the other side of the relationship in the disassembled object value array and thus the object was considered null and it was always loaded from the database.
We did find a class called SpecialOneToOneType.java that implemented what we believe was a better one-to-one caching mechanism. We copied over the assemble and disassemble methods to return the proper identifier and the ID was then put into the disassembled object array.
Thus when the object was re-constructed, Hibernate was able to check the cache for the object using the ID of the one-to-one and if that ID was in the cache it was returned. Doing this eliminated the database hits for the one-to-one relationships where the object was cached.
In our testing we have not yet run into any problems, but I would like to know if doing this will cause us other problems down the road that we have not yet seen. Is there any particular reason why Hibernate by default does not cache one-to-one relationships?
Mapping documents:
Code:
<class name="com.domain.entity.Person" table="PERSON">
... id and more here ...
<property name="gender" type="java.lang.String" column="GENDER" length="50" not-null="true"/>
<one-to-one name="user" class="com.authoria.domain.entity.User" property-ref="person" />
... more ...
</class>
<class name="com.domain.entity.User" table="DOMAIN_USER">
<property name="login" type="java.lang.String" column="LOGIN" length="50" not-null="true" unique="true"/>
<many-to-one name="person" class="com.domain.entity.Person" column="PERSON_ID" not-null="true" />
</class>