首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Spring OpenSessionInViewFilter 日誌詳解:Hibernate Session 生命週期

     編輯:程式設計綜合問答

日誌內容

DEBUG [qtp12189822-41] OpenSessionInViewFilter.doFilterInternal(181) | Opening single Hibernate Session in OpenSessionInViewFilter
DEBUG [qtp12189822-41] MpcFilterSecurityInterceptor.beforeInvocation(184) | Public object - authentication not attempted
DEBUG [qtp12189822-41] OpenSessionInViewFilter.doFilterInternal(207) | Closing single Hibernate Session in OpenSessionInViewFilter

作用機制

OpenSessionInViewFilter 是 Spring 提供的過濾器,用於實現「開放會話在視圖中」模式。其核心流程:

  1. 請求進入:過濾器 doFilterInternal 開啟一個 Hibernate Session,並綁定到當前線程(ThreadLocal)。
  2. 業務處理:Controller、Service、DAO 正常使用該 Session 進行數據庫操作。由於 Session 仍開啟,支持延遲加載(lazy=true)、級聯查詢等特性,避免視圖渲染時出現 LazyInitializationException。
  3. 視圖渲染:JSP/Thymeleaf 等視圖技術可自由訪問關聯對象(如 user.getOrders()),Session 仍可用。
  4. 請求結束:過濾器在 finally 塊中關閉 Session,釋放資源。

日誌對應關係

  • Opening single Hibernate Session → 請求開始,開啟 Session。
  • Public object - authentication not attempted → 安全攔截器判定為公共資源,跳過認證(與 Session 無直接關係)。
  • Closing single Hibernate Session → 請求結束,關閉 Session。

配置建議

在 web.xml 中註冊過濾器,並確保映射路徑覆蓋所有需要延遲加載的請求:

<filter>
    <filter-name>openSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>openSessionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

注意:Hibernate 5.x 使用 org.springframework.orm.hibernate5.support.OpenSessionInViewFilter,舊版本對應 hibernate4 或 hibernate3 包路徑。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved