servlet+Spring+hibernate请求线程绑定hibernate的session控制懒加载-OpenSessionInViewFilter
程序员文章站
2022-07-14 12:05:02
...
1、配置web.xml
<!-- 监听器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- -->
<!--Hibernate Open Session in View Filte -->
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<!-- singleSession默认为true,若设为false则等于没用OpenSessionInView -->
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2、获取applicationprivate static final long serialVersionUID = 7178222076194777660L;
UserServiceImpl userService;
IRoleService roleService;
@Override
public void init() throws ServletException {
//获取application必须使用在web.xml中实例化的application,要不然spring无法过滤url
ApplicationContext app=WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
userService = app.getBean("UserServiceImpl", UserServiceImpl.class);
roleService=app.getBean(RoleServiceImpl.class);
}
接下来就是使用dao进行增删改查了,这样不用自己控制懒加载,交给spring控制;不过这样有个很大的弊端就是一旦,用户的网络不好并且高并发的话,会长久占用连接,非常耗损服务器资源;