I've got a one-to-many relationship and every time I try to access the collection I get "org.hibernate.LazyInitializationException failed to lazily initialize a collection of role: ... no session or session was closed". The trick is that session IS open. I use ServletFilter to handle session management and have explicitly checked the state of the session anyway.
Here is the piece of code which throws the exception:
Code:
public void addNomination(Nomination nomination) {
Session session = Init.getSessionFactory().getCurrentSession();
logger.debug("Session connected: " + session.isConnected()); //prints true
logger.debug("Session open: " + session.isOpen()); // prints true
logger.debug("Object initialized: " + Hibernate.isInitialized(this.nominations)); // prints false
//Hibernate.initialize(this.nominations); // throws the "session disconnected" exception if left uncommented
nomination.setCycle(this);
this.getNominations().add(nomination); // throws the LazyInitializationException exception
}
Hibernate version:
Hibernate 3.1
Mapping documents:
<class name="Cycle" table="cycle">
<cache usage="read-write"/>
<id name="id">
<generator class="native"/>
</id>
<set name="nominations" table="nomination" cascade="all-delete-orphan" inverse="true" lazy="true">
<cache usage="read-write"/>
<key column="cycle_id" not-null="true"/>
<one-to-many class="Nomination"/>
</set>
</class>
<class name="Nomination" table="nomination" lazy="true">
<cache usage="read-write"/>
<id name="id"><generator class="native"/></id>
<many-to-one name="cycle" column="cycle_id" cascade="none" not-null="true"></many-to-one>
</class>
Full stack trace of any exception that occurs:
[13/02/06 12:04:11:152 EST] 2f03744f LazyInitializ E org.hibernate.LazyInitializationException failed to lazily initialize a collection of role: Cycle.nominations, no session or session was closed
[13/02/06 12:04:11:167 EST] 2f03744f LazyInitializ E org.hibernate.LazyInitializationException TRAS0014I: The following exception was logged org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: Cycle.nominations, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:343)
at org.hibernate.collection.AbstractPersistentCollection.write(AbstractPersistentCollection.java:183)
at org.hibernate.collection.PersistentSet.add(PersistentSet.java:165)
at Cycle.addNomination(Cycle.java:94)
...