views:

195

answers:

3

Hi All

When trying to get items from db, I got this error:

13:00:13.876 [7838526@qtp-204712603-0] ERROR o.h.LazyInitializationException - failed to lazily initialize a collection of role: bo.myobj, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: de.myob.linkedstuff, no session or session was closed

I understand that with switching to eager instead of lazy loading solves this problem, e.g.

@OneToMany(mappedBy = "myobj", cascade = CascadeType.ALL, fetch=FetchType.EAGER)

and I also understand that eager loading is discouraged. What is the best practitce in order to cope with this issue?

A: 

I am pretty sure this occurs when there is no active transaction.

Read the spring reference part about Declarative Transaction Management

Usually it boils down to your service method or class needing the @Transactional annotation if you use annotations or otherwise proper xml configuration of <tx:advice>.

seanizer
Sorry, I have checked all beans - @Transactional is present in all DAO methods ... my xml looks fine too
Thanks for downvoting. What I meant is: are you still inside the transactional scope, when you access the collection? Because that's probably not happening inside a dao method, is it?
seanizer
This doesn't deserve a downvote IMO. +1 to counterbalance.
Pascal Thivent
+1  A: 

This is a common problem, usually caused by rendering the view after the hibernate Session is closed. A common solution is to use the Open Session In View pattern, which will keep the hibernate session open for the lifetime of the web request.

Spring comes with a filter that implements this pattern. To enable it for all JSP files in your application, for example, add something like this to your web.xml:

<filter>
    <filter-name>osivFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>osivFilter</filter-name>
    <url-pattern>*.jsp</url-pattern>
</filter-mapping>
Jason Day
I inserted the lines, however, the laziiniterror persists :-(
+2  A: 

Better separation between the persistence and other layers. Make sure the objects produced by the persistence layer do not include any reference to Hibernate.

The article Hibernate, Get Out of My POJO! may be helpful.

Kwebble
Thanks for the tip, I guess that is the right strategy. However, I have been running into so many issues since I have started using an ORM that I wonder if there is any benifit using *any* ORM ... sorry, just *had* to mention that :-(
@erlord: Feel free to not use an ORM (at least not one with a defined persistence context) then :) And good luck!
Pascal Thivent