延遲加載即懶加載:關聯對象(如 @OneToMany 集合)在首次訪問時才發起 SQL 查詢,而非加載主對象時即刻加載。適用於數據量大、不常訪問關聯的場景,減少內存佔用與並發壓力。
// Service 層
Grade grade = gradeDao.findById(1); // 事務結束,Session 關閉
// 視圖層 (JSP/Thymeleaf)
for (Student s : grade.getStudents()) { // 拋出 LazyInitializationException
out.println(s.getName());
}
異常信息:failed to lazily initialize a collection of role: ... no session or session was closed。
在 web.xml 中配置 Spring 提供的過濾器,將 Session 生命周期延長至整個 HTTP 請求結束:
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
注意:Hibernate 5.x 包路徑為 org.springframework.orm.hibernate5,4.x 為 hibernate4,3.x 為 hibernate3。
Hibernate.initialize(proxy) 或 FETCH JOIN 顯式預加載所需關聯。@EntityGraph 精確控制加載範圍。