Tuesday, April 5, 2011

org.hibernate.LazyInitializationException: failed to lazily initialize a collection


org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: acme.domain.model.Bla.mumbles, 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.read(AbstractPersistentCollection.java:86)
at org.hibernate.collection.PersistentSet.iterator(PersistentSet.java:163)




Entity Bla contains a collection of Mumbles. The OneToMany annotation by default uses a LAZY loading approach.

If in your client layer you try to do a bla.getMumbles(), you get the exception LazyInitializationException. The session was closed in the EJB, and in the client you have only a detached entity.
To avoid the problem, in the EJB do a

bla.getMumbles().size();

(bla.getMumbles() is not enough!)


This will explicitly load ALL mumbles and the client will be happy.

No comments: