关于 OpenSessionInVewFilter jsp 页面N+1 的问题, 不知道大家有没有好的解决方法。
例如在页面 会产生 ........... where studentid = xxx
我用了 EhCache 缓存 ,不过好像还是不能解决这个问题,不知各位大侠是怎么解决的 ?
1.性能未必不好,理由是,假设一个页面显示10个学生,但是这10个学生分别属于3个老师,那最多只产生3条sql去查老师的数据,因为session一直开着,缓存中应该就有的。
2.虽然理论上1中说的不错,但是实际做的时候,最好自己控制,延迟加载一般都是针对一个学生的对象操作中尽量少的访问数据库。但是你这个需求就是要批量的取数据了,所以就针对这个查询单独写一个hql,在hql中显示声明join teacher,一条sql就搞定了。
楼住,我发的一个关于OpenSessionInVewFilter的配置问题没有人回答,现在想在此向你请教一下。
我的开发环境是:Struts1.1+Spring2.0+Hibernate3.0
我在Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- OpenSessionInViewFilter开始 -->
<filter>
<filter-name>opensession</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!-- OpenSessionInViewFilter 结束-->
<!-- 定义Filter,解决struts中文问题 -->
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>com.filter.SetCharacterEncodingFilter</filter-class>
<init-param>
<!-- 定义编码格式,我用的是GBK -->
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
<init-param>
<!-- innore参数是在过滤器类定义的 -->
<param-name>ignore</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!-- Filter 定义结束 -->
<filter-mapping>
<filter-name>opensession</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<servlet-name>action</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<servlet-name>*.jsp</servlet-name>
</filter-mapping>
action
org.apache.struts.action.ActionServlet
config
/WEB-INF/struts-config.xml
debug
3
detail
3
0
action
*.do
index.jsp
但延迟加载还是会出现问题:
failed to lazily initialize a collection of role: com.gzsz.vo.HotelInfo.roomInfos, no session or session was closed
想问一下,我上面的Web.xml配置有什么问题吗?还是其它地方出现了问题?
第一次配置这个东西,在网上查找了很多东西,但是还没有配置成功,盼望有人可以指点迷津,谢谢。
使用OpenSessionInVewFilter 的初衷就是因为延迟加载的问题。所以配置文件如果设置了lazy="true"的话,又想取出关联,就会出现N+1。如果你不想N+1的话,可以将 student 与 teacher 关联断开,或将关联设置为lazy="false"。
chengkey 你是否自己封装的代码有关闭session的操作,比如像下面的代码:
[code="java"]
hibernate.execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
String deleteClassName = cls.toString().substring(
cls.toString().lastIndexOf(".") + 1);
Transaction tx = session.beginTransaction();
int deletedEntities = session.createQuery(
"delete " + deleteClassName).executeUpdate();
tx.commit();
session.close();
log.debug("deleted " + deletedEntities + " " + deleteClassName
+ "s");
return null;
}
});
[/code]