Spring对于延迟加载问题的解决
Spring提供了延迟加载问题的解决方法
什么是延迟加载?
延迟加载:lazy(懒加载)
执行到该行代码的时候不会发送语句,真正使用这个对象的属性的时候才会发送sql语句进行查询。
- 类级别延迟加载:指的是是通过load方法查询某个对象的时候是否采用延迟,通过class标签上的lazy来配置。
- 关联级别的延迟加载:指的是查询某个对象的关联对象的时候,是否采用延迟加载。session.get(Customer.class,1l) , customer.getLinkMans();
SSH整合中那些地方会出现延迟加载的问题?
- 使用load方法查询某一个对象的时候(不常用)
- 查询到某个对象以后,显示其关联对象(频繁)
延迟加载问题产生的原因:
Hibernate的事务session.beginTransaction(),加在业务层。由于延迟加载,在web层获取LinkMan所关联的客户信息时才发送语句,但此时session已经在业务层关闭了,关联的对象没有被查询,延迟加载出现问题。
Dao层的解决方案:关闭延迟加载:lazy=false,一查联系人,就将客户查出来。开发不适用。
Spring的解决方案:
在核心过滤器前面加一个OpenSessionInViewFilter过滤器,在web层开启session,web层中的操作由脱管态变成持久态。
延迟加载异常示范:
访问:http://localhost:8889/ssh2/customer_findById.action
解决方法:在web.xml配置一个过滤器
测试:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>ssh1</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 解决延迟加载问题的过滤器,要在核心过滤器前面。在web层开启session,web层中的操作由脱管态变成持久态 --> <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>*.action</url-pattern> </filter-mapping> <!-- Spring的核心监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 用来加载Spring配置文件的路径,默认是/ssh1/WebContent/WEB-INF/* --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- struts2的核心过滤器 --> <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>