I have a many-to-many relationshop with the approach suggested on the page
http://www.hibernate.org/118.html#A10
Hibernate version: 3.x
Mapping documents:
Code:
<class name="User" table="user">
<id name="id" type="int" unsaved-value="null" >
<generator class="sequence">
<param name="sequence">user_id_seq</param>
</generator>
</id>
<!-- -->
<set name="relationship" table="relationship" cascade="all">
<key column="user_id"/>
<composite-element class="Relationship">
<property name="annotation" type="string"/>
<property name="comment" type="string"/>
<many-to-one name="foo" class="Foo" not-null="true" column="foo_id"/>
</composite-element>
</set>
</class>
Here is the problem. If I leave the mapping as the above, I will get the following exception when the getRelationships method is called.
Quote:
LazyInitializationException: - failed to lazily initialize a collection of role: com.xyz.abc.domain.User.relationship, no session or session was closed
No a fetch statement is issued for the relationship table.
This problem can be resolved by adding the lazy="false" statement in the set as many of you already know. That, however, would cause another problem. Whenever the User class is used in other objects, the relationship will get loaded even the data is not needed. I observe a quite interesting scenario within the situation. I will describe it later.
A solution I can think of is to leave the mapping file as it is and enforce Hiberate to issue a fetch statement on Relationship. But, how this can be done?