ssh專案中遇到的懶載入的問題(終於解決啦!!!)
轉載自:http://hellotommy.iteye.com/blog/809205
hibernate3.3.2+spring3.0.3+struts2.2.1
懶載入(Load On Demand)是一種獨特而又強大的資料獲取方法,它能夠在使用者滾動頁面的時候自動獲取更多的資料,而新得到的資料不會影響原有資料的顯示,同時最大程度上減少伺服器端的資源耗用。(百度說的)
通俗點,就是在找一個物件時不找出與他關聯的物件,而是在需要相關聯物件(或其屬性)時才去資料庫中找,也稱之為延遲載入。
一般來講,我們是在many-to-one 的many設定lazy=false,這是hibernate自身提供給我們的。
後來spring關起來session,我們可以換一種方式:OpenSessionInViewFilter
OpenSessionInViewFilter是Spring提供的一個針對Hibernate的一個支援類
一般我們可以這麼在web.xml中直接配置
Xml程式碼- <!-- Spring提供的避免Hibernate懶載入異常的過濾器
- 讓Session在請求解釋完成之後再關閉,從而避免懶載入異常 -->
- <filter>
-
<filter-name>openSessionInViewFilter</
- <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>openSessionInViewFilter</filter-name>
- <url-pattern>/*</url-pattern>
-
</filter-mapping
這樣就省去了很多麻煩,就不需要在每一個many地方設定lazy=false了
這個方法應該很流行,我也是網上找來的。但偏偏我就是新手,直接拿過來用,專案部署了N次都不起效果,真是鬱悶。每次報錯:org.hibernate.LazyInitializationException: could not initialize proxy - no Session。
很明顯,session關閉了。悲劇
當時就崩潰,為什麼網上都這麼說,卻總是錯誤呢。
突然恍然大霧。
既然spring管起了sessionFactory,獲得session必須也通過他才對呀,所以這部分的mapping 也應該放在struts2的mapping後面,經過這個類,然後執行真正的Action程式碼,最後根據情況將Hibernate的Session進行關閉。
下面是完整的web.xml:
Xml程式碼- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <!-- struts2 -->
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>
- org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
- </filter-class>
- </filter>
- <!-- spring 整合struts2 -->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:daoContext.xml,classpath:actionContext.xml,classpath:serviceContext.xml,classpath:applicationContext.xml</param-value>
- </context-param>
- <!-- Spring提供的避免Hibernate懶載入異常的過濾器
- 讓Session在請求解釋完成之後再關閉,從而避免懶載入異常 -->
- <filter>
- <filter-name>openSessionInViewFilter</filter-name>
- <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
- </filter>
- <!-- 以下2個mapping不可以調換位置 -->
- <filter-mapping>
- <filter-name>openSessionInViewFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>*.action</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
ok,這樣就省去在每個many配置lazy了。