標籤:inline prepare filter top etag spring hiberna add 功能
之所以要寫這個,是因為最近碰到了一個消極式載入的 load() 導致出現 noSession 的異常。
解決這個問題需要用到一個本地線程的對象,也就是 ThreadLocal 類,之前寫過關於這個對象,可以看這個部落格【本地線程 ThreadLocal 類】
我在資料層中封裝了一個 load() 方法,根據使用者 Id 擷取使用者物件:
public UserModel get(Long uuid) { return this.getHibernateTemplate().load(UserModel.class, uuid); //return this.getHibernateTemplate().get(UserModel.class, uuid); }
當在業務層調用了這個方法後,獲得一個 userModel 對象,當展示使用者資訊時,就會報出 noSession 問題,
public String get(){ //報出了 org.hibernate.LazyInitializationException: could not initialize proxy - no Session異常 UserModel temp = userEbi.get(1L); System.out.println(temp.getName()); System.out.println(temp.getAge()); return "haha"; }
報出的異常如下:
這是因為資料層提供的 load() 方法具有消極式載入的特性,也就是獲得對象只有 OID ,其他的資訊都沒有,只有當需要的時候才會去查詢(這叫二次查詢,消極式載入其他資料),如果二次查詢之前,這個只具有 OID 的對象傳遞到了業務層(如果在事務關閉session之前立馬進行二次查詢,就不會出問題),此時對象仍是一個消極式載入對象(只具有 OID),如果傳遞到了表現層(action內),此時該對象依然是消極式載入對象(但此時早在業務層,事務就已經將session關閉了,一旦要進行二次查詢就會報異常,因為session對象已經被重新整理了,也就是串連斷開了,session中儲存的資料早已丟失)。
但是在表現層使用二次查詢是比較正常的,也就是要做到當前session不關閉,直到一次請求完成才關閉。這時用到的一個技術就是 openSessionInView
這需要在 web.xml 中配置一個過濾器,用於將每個請求對象 request 和 session 對象綁定在一起(這裡的session是與資料庫互動的session,並不是瀏覽器的session會話),至於session的關閉,在一次請求結束時 session 會被自動關閉,這時註解的事務的任務就是開啟事務,重新整理事務;關閉事物的功能交給了 OpenSessionInViewFilter 這個類了,因為這個過濾器配置在一個,請求對象 request 最先接觸到它,請求結束時的最後一個過濾器也是它(這就是過濾器鏈了,往返要都過濾一次)。代碼在下面:(一定要將 OpenSessionInViewFilter 配置在所有過濾器的前面)
<?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"> <!-- applicationContext對象載入僅載入一次,伺服器啟動時載入,使用web中的監聽器機制 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- OpenSessionInView解決noSession問題,一定要配置在核心過濾器的前面 --> <filter> <filter-name>openSessionInView</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openSessionInView</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- struts核心過濾器 --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>
Hibernate 中 load() 方法導致的 noSession 異常