This is asked many times in SO. But they didn't solve my issue so posting again.
Getting following exception while trying to access my application
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.wpt.models.Item.itemCategory, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:575)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:214)
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:554)
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:142)
at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:294)
at org.apache.taglibs.standard.tag.common.core.ForEachSupport.toForEachIterator(ForEachSupport.java:348)
at org.apache.taglibs.standard.tag.common.core.ForEachSupport.supportedTypeForEachIterator(ForEachSupport.java:224)
at org.apache.taglibs.standard.tag.common.core.ForEachSupport.prepare(ForEachSupport.java:155)
at javax.servlet.jsp.jstl.core.LoopTagSupport.doStartTag(LoopTagSupport.java:256)
web.xml
<filter>
<filter-name>HibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>hibernate4AnnotatedSessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>HibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Spring config:
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="hibernate4AnnotatedSessionFactory">
</bean>
Item.java
@Entity
@Table(name="item")
public class Item {
@OneToMany(mappedBy="item", fetch=FetchType.LAZY, cascade=CascadeType.ALL)
private List<ItemCategory> itemCategory = new ArrayList<ItemCategory>();
}
ItemServiceImpl.java
@Override
@Transactional(readOnly=true)
public List<Item> getItemsByCategory(int categoryId) {
return itemDAO.getItemsByCategory(categoryId);
}
In all of the blogs, it's suggested to either go for EAGER
fetch, or use OpenSessionInViewFilter
with @Transactional
support.
It works will if I use EAGER
fetch. But not working the other way. I have implemented all service methods with @Transactional
annotation. What mistake I am doing here? Can someone please help?