OpenSessionInViewFilter与Write operations are not allowed in read-only mode 独门问题解决之道

  博主大三在实验室项目中使用 Spring 整合 Hibernate, 在懒加载的情况下,会出现一个异常,但为了查询效率,又需要利用懒加载用于关联表,查阅了网上资料说是在web.xml文件中加入一个过滤器OpenSessionInViewFilter如下方式
<!-- 配置Spring的OpenSessionInViewFilter过滤器,以解决Hibernate的懒加载异常(LazyInitializationException) -->  
    <filter>  
      <filter-name>OpenSessionInViewFilter</filter-name>  
  <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>  
   </filter>  
    <filter-mapping>  
       <filter-name>OpenSessionInViewFilter</filter-name>  
       <url-pattern>*.action</url-pattern>  
   </filter-mapping> 
好吧,这个真是害人不浅,强烈谴责要别人这么使用 OpenSessionInViewFilter还发布在网上的人,产生的结果就是发生Write operations are not allowed in read-only mode异常错误,害的我拖慢项目进度,我也是用了这个看了查询没事就洗洗睡了,没知道第二天就被实验室的师兄怒骂,问我做了什么,现在不能增删改了,好吧,我又只要在网上查方法,网上大部分给的解决方案是这个
 <filter>
     <filter-name>OpenSessionInViewFilter</filter-name>
     <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
  		<init-param>
  			<param-name>flushMode</param-name>
  			<param-value>AUTO</param-value>
  		</init-param>
  	</filter>
	<filter-mapping>
    <filter-name>OpenSessionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
	</filter-mapping>


对的这个的确消除了Write operations are not allowed in read-only mode错误,大家不要以为结束了,我在做了增删改操作后发现执行成功了,但数据库里的数据根本没有变化,说明了什么,说明这个方法只对了一半,还不报错!!,我们梳理一下,你的操作在逻辑层成功了,但是事物根本没有提交!!好明白这个问题就好办了,说明在service层和dao层两个之间出问题,我们开启debug模式,发现在service中参数也传递给dao层了,dao层也执行了,为什么就是不能成功呢?事物操作失败到底出现在哪,于是我开启了笨办法,在service层加入事物,发现这下成功了,这下知道了,所以解决问题是在service加入事物注解如下

@Service
@Transactional(readOnly=true,propagation=Propagation.REQUIRED)

好吧bug解决了,洗洗睡吧

猜你喜欢

转载自blog.csdn.net/qq_16651845/article/details/51582249