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?
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>
.
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>
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.
精彩评论