Web site translator - 308 APPENDIX C n HIBERNATE AND SPRING APPENDIX

308 APPENDIX C n HIBERNATE AND SPRING APPENDIX C n HIBERNATE AND SPRING Listing C-16. Wrapping the DAO Implementation Bean with Appropriate Transactionality

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 properties 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 practical 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 configuration file or an OpenSessionInViewFilter configured in your web.xmlfile, 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).
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.

Leave a Reply