在出现Hibernate错误:
could not initialize proxy - no Session
时,是因为使用load方法得到实体对象,使用的是代理对象,只有在执行某个getxxx()方法时才发出SQL语句查询数据,所以在退出dao层之后,session已经关闭,无法再继续发出SQL。
解决方法:
在web.xml中加上一个filter:openSessionInView。这个过滤器的作用是把打开和关闭Session的操作交给View来执行。避免数据还没拿到就关闭了Session.
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
这个filter要放在struts的filter之前。
在配置了这个filter之后,又出现了如下错误:
Write operations are not allowed in read-only mode
看了大神的解释,是因为这个filter默认会把FlushMode设置成MANUAL,在这种设置的情况下,会把事务处理设置成readonly状态,这样在进行数据的删除和更改的时候就会出错。所以只要在openSessionInView中设置flushMode为AUTO,就能解决。修改后如下:
<filter>
<filter-name>openSessionInView</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>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>