您的位置:首页 > 编程语言 > Java开发

Hibernate和spring结合的OpenSessionInViewFilter引起的错误解决

2013-10-29 20:20 453 查看
使用Spring提供的OpenSessionInView而引起的Writeoperationsarenotallowedinreadonlymode(FlushMode.NEVER)错误解决:
在没有使用Spring提供的OpenSessionInView情况下,因需要在service(orDao)层里把session关闭,所以lazyloading为true的话,要在应用层内把关系集合都初始化,如company.getEmployees(),否则Hibernate抛sessionalreadyclosedException;OpenSessionInView提供了一种简便的方法,较好地解决了lazyloading问题.
它有两种配置方式OpenSessionInViewInterceptor和OpenSessionInViewFilter(具体参看SpringSide),功能相同,只是一个在web.xml配置,另一个在application.xml配置而已。
OpenSessionInView在request把session绑定到当前thread期间一直保持hibernatesession在open状态,使session在request的整个期间都可以使用,如在View层里PO也可以lazyloading数据,如${company.employees}。当View层逻辑完成后,才会通过Filter的doFilter方法或Interceptor的postHandle方法自动关闭session。
OpenSessionInViewInterceptor配置
<beans>
<beanname="openSessionInViewInterceptor"
class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
<propertyname="sessionFactory">
<refbean="sessionFactory"/>
</property>
</bean>
<beanid="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<propertyname="interceptors">
<list>
<refbean="openSessionInViewInterceptor"/>
</list>
</property>
<propertyname="mappings">




..
</property>
</bean>



</beans>

OpenSessionInViewFilter配置
<web-app>



<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>*.do</url-pattern>
</filter-mapping>



</web-app>
很多人在使用OpenSessionInView过程中提及一个错误:
org.springframework.dao.InvalidDataAccessApiUsageException:Writeoperations
arenotallowedinread-onlymode(FlushMode.NEVER)-turnyourSessioninto
FlushMode.AUTOorremove'readOnly'markerfromtransactiondefinition
看看OpenSessionInViewFilter里的几个方法

protectedvoiddoFilterInternal(HttpServletRequestrequest,
HttpServletResponseresponse,FilterChainfilterChain)
throwsServletException,IOException{
 SessionFactorysessionFactory=lookupSessionFactory();
 logger.debug("OpeningHibernateSessioninOpenSessionInViewFilter");
 Sessionsession=getSession(sessionFactory);
 TransactionSynchronizationManager.bindResource(
  sessionFactory,newSessionHolder(session));
 try{
  filterChain.doFilter(request,response);
 }
 finally{
 TransactionSynchronizationManager.unbindResource(sessionFactory);
 logger.debug("ClosingHibernateSessioninOpenSessionInViewFilter");
 closeSession(session,sessionFactory);
 }
}

protectedSessiongetSession(SessionFactorysessionFactory)
throwsDataAccessResourceFailureException{
 Sessionsession=SessionFactoryUtils.getSession(sessionFactory,true);
 session.setFlushMode(FlushMode.NEVER);
 returnsession;
}

protectedvoidcloseSession(Sessionsession,SessionFactorysessionFactory)
throwsCleanupFailureDataAccessException{
 SessionFactoryUtils.closeSessionIfNecessary(session,sessionFactory);
}

可以看到OpenSessionInViewFilter在getSession的时候,会把获取回来的session的flushmode设为FlushMode.NEVER。然后把该sessionFactory绑定到TransactionSynchronizationManager,使request的整个过程都使用同一个session,在请求过后再接除该sessionFactory的绑定,最后closeSessionIfNecessary根据该session是否已和transaction绑定来决定是否关闭session。在这个过程中,若HibernateTemplate发现自当前session有不是readOnly的transaction,就会获取到FlushMode.AUTOSession,使方法拥有写权限。

publicstaticvoidcloseSessionIfNecessary(Sessionsession,SessionFactorysessionFactory)
throwsCleanupFailureDataAccessException{

if(session==null||
TransactionSynchronizationManager.hasResource(sessionFactory)){
return;
}
logger.debug("ClosingHibernatesession");
try{
session.close();
}
catch(JDBCExceptionex){
//SQLExceptionunderneath
thrownewCleanupFailureDataAccessException("CouldnotcloseHibernatesession",ex.getSQLException());
}catch(HibernateExceptionex){
thrownewCleanupFailureDataAccessException("CouldnotcloseHibernatesession",ex);
}
}

也即是,如果有不是readOnly的transaction就可以由Flush.NEVER转为Flush.AUTO,拥有insert,update,delete操作权限,如果没有transaction,并且没有另外人为地设flushmodel的话,则doFilter的整个过程都是Flush.NEVER。所以受transaction保护的方法有写权限,没受保护的则没有。
采用spring的事务声明,使方法受transaction控制
<beanid="baseTransaction"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
abstract="true">
<propertyname="transactionManager"ref="transactionManager"/>
<propertyname="proxyTargetClass"value="true"/>
<propertyname="transactionAttributes">
<props>
<propkey="get*">PROPAGATION_REQUIRED,readOnly</prop>
<propkey="find*">PROPAGATION_REQUIRED,readOnly</prop>
<propkey="load*">PROPAGATION_REQUIRED,readOnly</prop>
<propkey="save*">PROPAGATION_REQUIRED</prop>
<propkey="add*">PROPAGATION_REQUIRED</prop>
<propkey="update*">PROPAGATION_REQUIRED</prop>
<propkey="remove*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>

<beanid="userService"parent="baseTransaction">

<propertyname="target">
<beanclass="com.phopesoft.security.service.impl.UserServiceImpl"/>
</property>
</bean>
对于上例,则以save,add,update,remove开头的方法拥有可写的事务,如果当前有某个方法,如命名为importExcel(),则因没有transaction而没有写权限,这时若方法内有insert,update,delete操作的话,则需要手动设置flushmodel为Flush.AUTO,如
session.setFlushMode(FlushMode.AUTO);
session.save(user);
session.flush();
尽管OpenSessionInView看起来还不错,其实副作用不少。看回上面OpenSessionInViewFilter的doFilterInternal方法代码,这个方法实际上是被父类的doFilter调用的,因此,我们可以大约了解的OpenSessionInViewFilter调用流程:request(请求)->opensession并开始transaction->controller->View(Jsp)->结束transaction并closesession.
一切看起来很正确,尤其是在本地开发测试的时候没出现问题,但试想下如果流程中的某一步被阻塞的话,那在这期间connection就一直被占用而不释放。最有可能被阻塞的就是在写Jsp这步,一方面可能是页面内容大,response.write的时间长,另一方面可能是网速慢,服务器与用户间传输时间久。当大量这样的情况出现时,就有连接池连接不足,造成页面假死现象。
OpenSessionInView是个双刃剑,放在公网上内容多流量大的网站请慎用。
.....................
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐