Java Reference
In-Depth Information
Listing C-16. Wrapping the DAO Implementation Bean with Appropriate Transactionality
<bean id="paperDao" parent="daoTxTemplate">
<property name="target">
<bean class="com.hibernatebook.spring.dao.PaperDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</property>
</bean>
Managing the Session
A familiar problem encountered when using Hibernate is the LazyInitializationException .
This occurs when you try to access the lazily loaded attributes of a detached entity—typically
when the session that loaded it has been closed. This causes problems in Spring when you
want to use information obtained from a DAO in a controller in the view to which it forwards
the request.
By default, a DAO derived from the HibernateDaoSupport class closes the session as soon
as any HibernateTemplate methods complete (or as soon as the session is released, if you are
not using HibernateTemplate ). Entities that have been retrieved from the DAO will therefore
become detached from their session. If they are then passed to a view—typically a JSP—your
client code will produce a LazyInitializationException when it tries to access any lazy prop-
erties of the entity that were not accessed prior to completion of the original DAO method
(or forced to load in some other way).
Clearly, marking all the properties of your entities as being eagerly loaded is not practi-
cal—and typically, it is not possible to determine in advance exactly which properties of your
entity should be actively loaded.
Instead, Spring provides a mechanism to implement the OpenSessionInView pattern of
behavior. This ensures that the Session object is retained until processing of the view is
complete. Only then is it closed—it must be closed at some point to ensure that your web
applications don't leak a Session for every user request!
The effect is that with either an OpenSessionInViewInterceptor in your Spring config-
uration file or an OpenSessionInViewFilter configured in your web.xml file, you can access
lazily loaded attributes of entities acquired from your DAOs without any risk of the dreaded
LazyInitializationException . Note that only one of the two options is required—they differ
only in their internal details, not the outcome of applying them.
Generally, we use the OpenSessionInViewInterceptor , as it is configured like any other
Spring bean. Our example application makes use of this to ensure that the lazily loaded
articles attribute of the Paper entity can be accessed from the JSP view implementations
(see Listing C-17).
Search WWH ::




Custom Search